突然要用到C程序里调用当前时间,来测试一段代码的运行时间。找了一下是否有可以调用的库函数,没想到真的有:gettimeofday。因为这里的这个应用蛮常用的,所以留个记录在此。
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 struct timeval
5 {
6 long tv_sec; /* 秒数 */
7 long tv_usec; /* 微秒数 */
8 };
9
10 struct timezone
11 {
12 int tv_minuteswest;
13 int tv_dsttime;
14 };
15
16 int gettimeofday(struct timeval *tv,struct timezone *tz);
17
18 void function()
19 {
20 // function to run some time consuming codes
21 }
22
23 int main(int argc, char *argv[])
24 {
25 struct timeval tpstart,tpend;
26 float timespend;
27
28 gettimeofday(&tpstart,NULL);
29 function();
30 gettimeofday(&tpend,NULL);
31 timespend = tpend.tv_sec - tpstart.tv_sec;
32 printf("Time Spend: %d", timespend);
33 return EXIT_SUCCESS;
34 }
2 #include <stdlib.h>
3
4 struct timeval
5 {
6 long tv_sec; /* 秒数 */
7 long tv_usec; /* 微秒数 */
8 };
9
10 struct timezone
11 {
12 int tv_minuteswest;
13 int tv_dsttime;
14 };
15
16 int gettimeofday(struct timeval *tv,struct timezone *tz);
17
18 void function()
19 {
20 // function to run some time consuming codes
21 }
22
23 int main(int argc, char *argv[])
24 {
25 struct timeval tpstart,tpend;
26 float timespend;
27
28 gettimeofday(&tpstart,NULL);
29 function();
30 gettimeofday(&tpend,NULL);
31 timespend = tpend.tv_sec - tpstart.tv_sec;
32 printf("Time Spend: %d", timespend);
33 return EXIT_SUCCESS;
34 }
来源:https://www.cnblogs.com/sjpisaboy/archive/2006/04/14/375605.html