Prayer

在一般中寻求卓越
posts - 1256, comments - 190, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

C中获取当前时间的函数

Posted on 2009-01-22 16:01 Prayer 阅读(2039) 评论(0)  编辑 收藏 引用 所属分类: C/C++
      突然要用到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 }

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理