加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

利用gettimeofday计算程序运行时间--精确到毫秒(/微秒)(timeval结构体)

(2014-06-26 17:16:15)
标签:

gettimeofdaytimeval

timeval

毫秒

运行时间

微秒

分类: c++
笔者在写一个测试c++程序运行时间的小函数时,用到了gettimeofday函数和timeval这个结构体,它可以精确到时间的微秒量级,此函数代码在linux下亲测可用,在windows下没试过,应该不行。

      在linux的man页中对gettimeofday函数的说明中,gettimeofday用法为:

       #includetime.h>

       int gettimeofday(struct timeval *tv, struct timezone *tz);

      DESCRIPTION
      The functions gettimeofday and settimeofday can get and set the time as
      well as a timezone. The tv argument is a timeval struct, as specified
      in :

struct timeval 结构体定义如下:
struct timeval {
              time_t       tv_sec;    
              suseconds_t   tv_usec;
            };

以下是利用gettimeofday计算程序运行时间的例子:


#include  

#include <<font color="#ff0000">sys/time.h>

long getCurrentTime()  

{  

   struct timeval tv;  

   gettimeofday(&tv,NULL);  

   return tv.tv_sec * 1000 + tv.tv_usec / 1000;  

}  

  

int main()  

{  

    long start = getCurrentTime();

    printf("c/c++ program:%ld\n",getCurrentTime()); 

    //设置延迟

    for (int i = 0; i<100000; ++i)

    {   }

    printf("The program has run %ld ms", getCurrentTime()-start);

    return 0;  

}

运行后就可以看到结果啦 http://www/uc/myshow/blog/misc/gif/E___6721EN00SIGG.gif~~

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有