在计算程序的耗时操作时,程序运行的时间特别的短,所以我们要获取的时间尽可能的准确。
1.使用time()获取当前时间。
头文件: #include <time.h>
函数 : time_t time(time *tm)
time()的返回值是从1970.01.01 00:00:00 到函数获取时间的一个毫秒数。
由于获取到的毫秒数不便于我们直观了解当前时间。
所以经常进行一些格式上的转换。通过localtime()的返回值stuct tm来设置。
struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};
2.对于更精确的时间我们采用gettiemofday()函数。
头文件: #include <sys/time.h>
函数 : int gettimeofday(struct timeval *tv, struct timezone *tz);
函数gettimeofday()和settimeofday()可以获得和设置时间以及时区。
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
};
这两个参数,通常我们只需要定义第一个结构体,第二个为NULL即可。
需要注意的是要获得最后的微秒数,需要将【tv_sec*1000000+tv_usec】
代码:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h>
4 #include <sys/time.h>
5
6 int main(void)
7 {
8 time_t tm;
9 struct tm *loctime;
10 struct timeval tv;
11
12 time(&tm);
13 loctime = localtime(&tm);
14 gettimeofday(&tv, NULL);
15
16 printf("\n");
17 printf("time() get the time is %ld s \n", tm);
18 printf("\n");
19 printf("ctime() get the time is %s", ctime(&tm));
20 printf("\n");
21 printf("localtime() get the time is %d-%d-%d %d:%d:%d \n",
22 loctime->tm_year+1900, loctime->tm_mon+1, loctime->tm_mday+1,
23 loctime->tm_hour, loctime->tm_min, loctime->tm_sec);
24
25 printf("\n");
26 printf("gettimeofday() get the time is %ld us \n",
27 tv.tv_sec*1000000 + tv.tv_usec);
28 printf("\n");
29
30 return 0;
31 }
运行结果: