您的位置:首页 > 其它

输出程序运行的时间(精确到微秒)

2014-10-09 18:03 183 查看
对于要求性能的代码,输出程序运行的时间还是很有必要的,而且需要较高的精确度,下面这个代码段就实现了此功能

注意:只限于Linux下使用,因为<sys/time.h>的缘故

#include <sys/time.h>
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
// 统计所用时间
unsigned int unTimeUse;

struct timeval stStartTime;
struct timeval stEndTime;

gettimeofday(&stStartTime, NULL);

int i = 10000;
while(i-- > 0);

gettimeofday(&stEndTime, NULL);
unTimeUse = 1000000*(stEndTime.tv_sec - stStartTime.tv_sec) +
stEndTime.tv_usec - stStartTime.tv_usec;

cout.setf(ios_base::fixed);
cout << "Use time: " << unTimeUse/1000000.0 << " sec" << endl;

return 0;
}


输出结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: