clock_gettime始终显示0

时间:2013-07-03 16:30:10

标签: c performance time

我想用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 );
  }

1 个答案:

答案 0 :(得分:2)

因为编译器会优化你的循环。在循环内做一些无法简化的事情(由编译器完成);所以创造一些结果。然后在循环之后使用(例如打印)此结果。

您还可以尝试在编译时关闭优化。但是,由于您当前的循环非常容易优化,这可能没有什么区别。

相关问题