时间获取函数
发布时间:2020-12-14 00:35:57 所属栏目:Linux 来源:网络整理
导读:目录 time函数 clock_gettime函数 gettimeofday函数 由Linux内核提供的基本时间是自1970-01-01 00:00:00 +0000 (UTC)这一特定时间以来经过的秒数,这种描述是以数据类型time_t表示的,我们称其为日历时间。 获得日历时间的函数有3个:time、clock_gettime和g
目录
由Linux内核提供的基本时间是自1970-01-01 00:00:00 +0000 (UTC)这一特定时间以来经过的秒数,这种描述是以数据类型time_t表示的,我们称其为日历时间。 time函数#include <time.h> //成功返回日历时间,出错返回-1;若time非NULL,则也通过其返回时间值 time_t time(time_t *time); #include <stdio.h> #include <string.h> #include <time.h> void print_time() { time_t seconds = time(NULL); printf("seconds = %ldn",seconds); } int main() { print_time(); return 0; } clock_gettime函数clock_gettime函数可用于获取指定时钟的时间,返回的时间通过struct timespec结构保存,该结构把时间表示为秒和纳秒。 #include <time.h> struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; //Link with -lrt. int clock_gettime(clockid_t clock_id,struct timespec *tsp); clock_id一般设置为 #include <stdio.h> #include <string.h> #include <time.h> void print_time() { time_t seconds; struct timespec tsp; seconds = time(NULL); printf("seconds = %ldn",seconds); clock_gettime(CLOCK_REALTIME,&tsp); printf("tsp.tv_sec = %ld,tsp.tv_nsec = %ldn",tsp.tv_sec,tsp.tv_nsec); } int main() { print_time(); return 0; } gettimeofday函数和clock_gettime函数类似,gettimeofday通过struct timeval结构返回日历时间,该结构把时间表示为秒和微妙。 #include <sys/time.h> struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; int gettimeofday(struct timeval *tv,struct timezone *tz); 需要注意的是,参数tz的唯一合法值是NULL。 #include <stdio.h> #include <string.h> #include <time.h> #include <sys/time.h> void print_time() { time_t seconds; struct timespec tsp; struct timeval tv; seconds = time(NULL); printf("seconds = %ldn",tsp.tv_nsec); gettimeofday(&tv,NULL); printf("tv.tv_sec = %ld,tv.tv_usec = %ldn",tv.tv_sec,tv.tv_usec); } int main() { print_time(); return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |