【问题标题】:clock() works well on debug version but won't work on release (C++ VS2010)clock() 在调试版本上运行良好,但在发布版本上不起作用(C++ VS2010)
【发布时间】:2011-12-22 08:45:50
【问题描述】:

这是我的代码:

// Start performance test clock
assert((start=clock())!=-1);

// Some reading and writing methods

// Get stop time
stop = clock();

cout << stop << endl;

// Calculate operation time
double result = (double)(stop-start)/CLOCKS_PER_SEC;

// Print result
cout << "--> Finished analysing in " << result << "s" << endl;

当我调试我的程序时效果很好,但是当我运行发布版本时, stop 接收的值比 start 小得多,结果是负数。

有什么想法吗?

【问题讨论】:

  • 发行版可能会进行大量优化,因此比调试版花费的时间要少得多。通常,调试版本不使用优化。如果您在发布配置中禁用优化会发生什么(确保之后重新启用它)?
  • @WTP:我怀疑任何编译器都可以很好地优化代码,以至于它可以及时返回!问题不仅在于获得较小的时间值,还在于获得负值。
  • 旁白:考虑使用Boost timer library

标签: c++ timer release clock


【解决方案1】:

start 的赋值不应该在assert 语句中。 assert 通常是发布版本中的无操作。所以在调试版本中,语句start=clock() 将被执行,但在发布版本中,它不会。所以它可能没有被初始化(取决于早期的代码和start 的声明)。通常希望避免使用具有副作用的assert 语句;它可能会导致调试和发布版本之间出现细微的差异/错误。

这样写可能会更好:

start = clock();
assert(start != -1);

【讨论】:

    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多