关于c:时间相关函数

1次阅读

共计 1592 个字符,预计需要花费 4 分钟才能阅读完成。

linux 工夫函数有不少,平时用的也比拟多,然而这些函数常常忘了,故记录下来,留作当前编程查问之用。

time 函数

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

此函数会返回从公元 1970 年 1 月 1 日的 UTC 工夫从 0 时 0 分 0 秒算起到当初所通过的秒数。如果 t 并非空指针的话,此函数也会将返回值存到 t 指针所指的内存. 产生谬误返回 -1.

clock_gettime

#include <sys/time.h>
int clock_gettime(clockid_t clock_t,struct timespec * tsp);

此函数用于获取指定的时钟工夫. 罕用如下 4 种时钟:
CLOCK_REALTIME 统以后工夫,从 1970 年 1.1 日算起
CLOCK_MONOTONIC 零碎的启动工夫,不能被设置
CLOCK_PROCESS_CPUTIME_ID 本过程运行工夫
CLOCK_THREAD_CPUTIME_ID 本线程运行工夫.
胜利返回 0,产生谬误返回 -1。

struct timespec 的构造如下:

struct timespec {
  time_t tv_sec; // seconds
  long tv_nsec; // and nanoseconds
};

当 clockid_t 为 CLOCK_REALTIME 时,clock_gettime 函数跟 time 函数性能相似。

gettimeofday 函数

#include <sys/time.h>

int gettimeofday (struct timeval * tp, void * tzp);

gettimeofday 返回胜利时函数将间隔 1970.1.1 的工夫存储在指针 tp 指向的地址中,struct timeval 的构造如下。tzp 依赖于相干 unix 平台实现来代表时区。返回值总是返回 0.

struct timeval {
  time_t tv_sec; // seconds
  long tv_usec; // microseconds
};

localtime 和 gmtime

#include <time.h>

struct tm * gmtime(const time_t * calptr);

struct tm * localtime(const time_t * calptr);

gmtime 和 localtime 两个函数将日历工夫转换为合成工夫,并将其存在 struct tm 构造中.

struct tm {int tm_sec;    /* 秒 – 取值区间为[0,59] */
int tm_min;    /* 分 - 取值区间为[0,59] */
int tm_hour;   /* 时 - 取值区间为[0,23] */
int tm_mday;   /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon;    /* 月份(从一月开始,0 代表一月)- 取值区间为[0,11] */
int tm_year;   /* 年份,其值等于理论年份减去 1900 */
int tm_wday;   /* 星期 – 取值区间为[0,6],其中 0 代表星期天,1 代表星期一,以此类推 */
int tm_yday;   /* 从每年的 1 月 1 日开始的天数 – 取值区间为[0,365],其中 0 代表 1 月 1 日,1 代表 1 月 2 日,以此类推 */
int tm_isdst;   /* 夏令时标识符,履行夏令时的时候,tm_isdst 为正。不履行夏令时的时候,tm_isdst 为 0;不理解状况时,tm_isdst()为负 */。long int tm_gmtoff;  /* 指定了日期变更线东面时区中 UTC 东部时区正秒数或 UTC 西部时区的负秒数 */
const char *tm_zone;   /* 以后时区的名字(与环境变量 TZ 无关)*/
};

localtime 将日历工夫转换老本地时区工夫,gmtime 则将日历工夫转换成协调对立的工夫构造。

mktime

函数 mktime 以 struct tm * 为参数,将 tm 构造代表的工夫转换为 time_t

#include <time.h>

time_t mktime(struct tm * tmptr)
正文完
 0