所以我在代码的开头得到时间,运行它,然后抽出时间。
struct timeval begin, end;
gettimeofday(&begin, NULL);
//code to time
gettimeofday(&end, NULL);
//get the total number of ms that the code took:
unsigned int t = end.tv_usec - begin.tv_usec;
现在我想以“**代码运行0.007秒”或类似的形式打印出来。
所以有两个问题:
1)t似乎包含6000的订单值,我知道代码没有花6秒的时间运行。
2)我怎样才能将t转换为double,因为它是unsigned int?或者是否有更简单的方式以我想要的方式打印输出?
答案 0 :(得分:15)
timeval
包含两个字段,秒部分和微秒部分。
tv_usec
( u 意味着希腊字母 mu ,代表微观)是微秒。因此当你得到6000时,那已经过了6000微秒。
tv_sec
包含秒部分。
要获得所需的值,请使用此代码:
double elapsed = (end.tv_sec - begin.tv_sec) +
((end.tv_usec - begin.tv_usec)/1000000.0);
确保在计算中包含tv_sec
部分。 gettimeofday
返回当前时间,因此当秒增加时,微秒将返回0,如果在代码运行时发生这种情况并且在计算中未使用tv_sec
,则会得到一个负数。
答案 1 :(得分:6)
1)那是因为usec
不是6000毫秒,而是6000微秒(6毫秒或6千分之一秒)。
2)试试这个:(double)t / 1000000
这会将t转换为double,然后除以一百万来找到秒数而不是微秒数。