【发布时间】:2013-07-01 11:04:21
【问题描述】:
我想用clock_gettime 测量挂钟时间,但每次运行我的代码时,它都会显示 0。这是为什么呢? (我希望我的结果以毫秒为单位。)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
int main( int argc, char **argv )
{
struct timespec start, stop;
unsigned long accum;
if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
perror( "clock gettime" );
exit( EXIT_FAILURE );
}
int i;
for(i=0; i<100000000; i++){int a = 3; int b = 100; int c = a*b;}
//system( argv[1] );
if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
perror( "clock gettime" );
exit( EXIT_FAILURE );
}
accum = (unsigned long)( (stop.tv_sec - start.tv_sec) * 1000) + (unsigned long)( (stop.tv_nsec - start.tv_nsec) / 1000000 ) +0.5;
printf( "%lu\n", accum );
return( EXIT_SUCCESS );
}
【问题讨论】:
-
en.wikipedia.org/wiki/Dead_code_elimination - 编译器正在完全删除你的循环。
-
计算
accum的方式只有在执行至少需要1 秒时才会看到非零值。for循环很可能已被优化。用scanf替换循环以增加延迟。 -
@Mysticial:好的,谢谢!:)) 关于毫秒的问题:我想知道
accum = (unsigned long)( (stop.tv_sec - start.tv_sec) * 1000) + (unsigned long)( (stop.tv_nsec - start.tv_nsec) / 1000000 ) +0.5;是否会给我毫秒? -
小心
stop.tv_nsec - start.tv_nsec。它可能会变成负数。 -
@meaning-matters 该结构分别为您提供秒和纳秒。所以它就像一个数字的两位数。如果你用数字减去
3.1 - 1.9,你会得到 2.-8。-8就是一个负面的例子。所以你需要把它带到下一个数字。 (或者在这种情况下,将其传播到 seconds 变量)
标签: c performance time