当前位置: 首页 > news >正文

Linux的时间操作

当涉及到时间操作时,Linux提供了一系列函数和结构体来处理时间的获取、转换和操作。

time_t 别名

time_t 是 C/C++ 中用来表示时间的类型,通常被定义为整数类型。它通常用来存储从纪元(通常是1970年1月1日)到某一特定时间点之间的秒数。

#include <time.h>time_t t;

time() 库函数

time() 函数用于获取当前时间的秒数,返回的时间是自纪元以来经过的秒数。

#include <time.h>time_t time(time_t *t);

示例用法:

time_t current_time;
time(&current_time);

tm 结构体

tm 结构体用于表示日期和时间信息,包括年、月、日、小时、分钟、秒等。它通常用于时间的转换和格式化。

#include <time.h>struct tm {int tm_sec;   // 秒int tm_min;   // 分int tm_hour;  // 时int tm_mday;  // 一个月中的某一天int tm_mon;   // 月份(0-11)int tm_year;  // 年份 - 1900int tm_wday;  // 一周中的某一天(0-6,周日为 0)int tm_yday;  // 一年中的某一天(0-365)int tm_isdst; // 夏令时标识
};

localtime() 库函数

localtime() 函数用于将时间戳(time_t 类型)转换为本地时间的 tm 结构体表示。

#include <time.h>struct tm *localtime(const time_t *timep);

示例用法:

time_t current_time;
struct tm *local_time;time(&current_time);
local_time = localtime(&current_time);

localtime_r() 函数

localtime_r() 函数与 localtime() 函数类似,但是它将结果存储在用户提供的 tm 结构体中,避免了线程安全性问题。

#include <time.h>struct tm *localtime_r(const time_t *timep, struct tm *result);

示例用法:

time_t current_time;
struct tm local_time;time(&current_time);
localtime_r(&current_time, &local_time);

mktime() 函数

mktime() 函数用于将 tm 结构体表示的时间转换为 time_t 类型的时间戳。

#include <time.h>time_t mktime(struct tm *timeptr);

示例用法:

struct tm timeinfo = {0};
timeinfo.tm_year = 121;  // 年份为2021
timeinfo.tm_mon = 0;     // 月份为1月
timeinfo.tm_mday = 1;    // 日期为1日time_t time = mktime(&timeinfo);

gettimeofday() 库函数

gettimeofday() 函数用于获取当前的时间以及时区信息。

#include <sys/time.h>int gettimeofday(struct timeval *tv, struct timezone *tz);

示例用法:

#include <sys/time.h>struct timeval current_time;
gettimeofday(&current_time, NULL);

程序睡眠

在Linux中,可以使用 sleep()usleep() 函数来使程序休眠指定的时间。

sleep() 函数

sleep() 函数用于使程序休眠指定的秒数。

#include <unistd.h>unsigned int sleep(unsigned int seconds);

示例用法:

sleep(5);  // 休眠5秒
usleep() 函数

usleep() 函数用于使程序休眠指定的微秒数。

#include <unistd.h>int usleep(useconds_t usec);

示例用法:

usleep(500000);  // 休眠500毫秒(即0.5秒)

以上是关于你提到的 Linux 时间操作相关内容的详细介绍。这些函数和数据结构在程序开发中经常用到,能够帮助开发人员处理时间相关的需求。

http://www.lryc.cn/news/305702.html

相关文章:

  • 2024-02-21 作业
  • 平台组成-监控服务
  • 探索分布式强一致性奥秘:Paxos共识算法的精妙之旅
  • 使用 ES|QL 优化可观察性:简化 Kubernetes 和 OTel 的 SRE 操作和问题解决
  • Docker 第十九章 : 阿里云个人镜像仓使用
  • 二、系统知识笔记-系统架构概述
  • 【高德地图】Android高德地图绘制标记点Marker
  • 每天一个知识点 - 如何快速熟悉后端项目
  • 如何将cocos2d-x js打包部署到ios上 Mac M1系统
  • pdffactory pro 8中文破解版
  • 常用ADB命令整理已经ADB键盘输入
  • buuctf_N1BOOK_粗心的小李
  • 爬取链家二手房房价数据存入mongodb并进行分析
  • 论文阅读:Ground-Fusion: A Low-cost Ground SLAM System Robust to Corner Cases
  • 一键获取电商平台商品信息,快速提高电商业务效率
  • vue 中实现音视频播放进度条(满足常见开发需求)
  • 【广度优先搜索】【网格】【割点】1263. 推箱子
  • 论文精读--GPT1
  • C/C++的内存管理(1)
  • C 标准库 - <stdlib.h>
  • Python中回调函数的理解与应用
  • 抖音数据挖掘软件|视频内容提取
  • PostgreSQL如何使用UUID
  • 网络原理 - HTTP/HTTPS(4)
  • Vue+SpringBoot打造在线课程教学系统
  • 数据存储-文件存储
  • 【Activiti7】全新Activiti7工作流讲解
  • C++ 学习(1)---- 左值 右值和右值引用
  • Redis能保证数据不丢失吗?
  • C++基础知识(六:继承)