【问题标题】:clock_gettime always shows 0clock_gettime 总是显示 0
【发布时间】: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


【解决方案1】:

因为编译器优化了你的循环。在循环中做一些不容易简化的事情(通过编译器);所以创造一些结果。然后在循环之后使用(例如打印)这个结果。

您也可以在编译时尝试关闭优化。但是由于您当前的循环很容易优化掉,这可能不会有什么不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    相关资源
    最近更新 更多