在C语言中可以使用函数gettimeofday()函数来得到精确时间。它的精度可以达到微妙,是C标准库的函数。
- #include<sys/time.h>
-
- int gettimeofday(struct timeval*tv,struct timezone *tz )
gettimeofday()会把目前的时间用tv 结构体返回,当地时区的信息则放到tz所指的结构中
1. timeval 结构体定义:
- struct timeval{
-
- long tv_sec; /*秒*/
-
- long tv_usec; /*微妙*/
-
- };
2. timezone 结构定义:
- struct timezone{
-
- int tz_minuteswest;/*和greenwich 时间差了多少分钟*/
-
- int tz_dsttime; /*type of DST correction*/
-
- }
3>在gettimeofday()函数中tv或者tz都可以为空。如果为空则就不返回其对应的结构体。
4>函数执行成功后返回0,失败后返回-1,错误代码存于errno中。
- #include<stdio.h>
- #include<sys/time.h>
- #include<unistd.h>
-
- void hello_world(void)
- {
- printf("Hello world!!!!\r\n");
- }
-
- int main(void)
- {
-
- struct timeval tv_begin,tv_end;
-
- gettimeofday(&tv_begin,NULL);
-
- hello_world();
-
- gettimeofday(&tv_end,NULL);
-
- printf(“tv_begin_sec:%d\n”,tv_begin.tv_sec);
-
- printf(“tv_begin_usec:%d\n”,tv_begin.tv_usec);
-
- printf(“tv_end_sec:%d\n”,tv_end.tv_sec);
-
- printf(“tv_end_usec:%d\n”,tv_end.tv_usec);
-
- return 0;
-
- }
//统计耗时,单位ms
int times = (tv_end.tv_sec*1000+tv_end.tv_usec/1000) - (tv_begin.tv_sec*1000+tv_begin.tv_usec/1000);
说明:在使用gettimeofday()函数时,第二个参数一般都为空,因为我们一般都只是为了获得当前时间,而不用获得timezone的数值
函数声明:time_t time (time_t *__timer);
其中time_t为time.h定义的结构体,一般为长整型
time函数返回的为unix时间戳,即从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。
如果参数__timer非空,会存储相同值到__timer指向的内存中。
函数声明:struct tm *localtime (const time_t *__timer);
tm为一个结构体,包含了年月日时分秒等信息
-
- #include <stdio.h>
- #include <time.h>
- int main ()
- {
- time_t t;
- struct tm * lt;
- time (&t);//获取Unix时间戳。
- lt = localtime (&t);//转为时间结构。
- printf ( "%d/%d/%d %d:%d:%d\n",lt->tm_year+1900, lt->tm_mon+1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);//输出结果
- return 0;
- }
-