1. C 库函数 - time()
C 库函数 time_t time(time_t *seconds) 返回自纪元 Epoch(1970-01-01 00:00:00 UTC)起经过的时间,以秒为单位。如果 seconds 不为空,则返回值也存储在变量 seconds 中。
time_t time(time_t *t);
参数:
- 参数seconds -- 这是指向类型为 time_t 的对象的指针,用来存储 seconds 的值。
- 返回值:以 time_t 对象返回当前日历时间。
测试代码:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time(NULL);
printf("自 1970-01-01 起的小时数 = %ld\n", seconds/3600);
return(0);
}
输出结果:

2. gettimeofday()
使用C语言编写程序需要获得当前精确时间(1970年1月1日到现在的时间),或者为执行计时,可以使用gettimeofday()函数。
函数原型:
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
说明:其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:
struct timeval
{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
timezone 参数若不使用则传入NULL即可。
测试代码:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
struct timeval start,end;
gettimeofday(&start,NULL);
sleep(1);//需要测定时间的代码部分
gettimeofday(&end,NULL);
suseconds_t msec = end.tv_usec-start.tv_usec;
time_t sec = end.tv_sec-start.tv_sec;
printf("time used:%u.%us\n",sec,msec);
return 0;
}
输出结果:

参考资料:
本文深入解析了C语言中的time()和gettimeofday()函数,详细介绍了这两个函数如何获取从1970年至今的时间,以及如何测量程序运行时间。文章通过示例代码展示了函数的使用方法。
1640

被折叠的 条评论
为什么被折叠?



