0

我在自己的代码中注意到了这一点,并决定使用 Boost.timer 附带的示例代码来验证它。也许它不适用于 tdm64 编译器?

结果如下:

% g++ --version
g++.exe (tdm64-1) 4.6.1
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

% 
% g++ -Wall -ggdb3 -o auto_cpu_timer_example boost_1_49_0/libs/timer/example/auto_cpu_timer_example.cpp -lboost_timer -lboost_chrono -lboost_system
% 
% g++ -Wall -ggdb3 -o timex boost_1_49_0/libs/timer/example/timex.cpp  -lboost_timer -lboost_chrono -lboost_system
%
% auto_cpu_timer_example.exe 
 0.000000s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (0.0%)
%
%
% ./timex -v auto_cpu_timer_example.exe 
 0.000000s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (0.0%)
command: "auto_cpu_timer_example.exe"
 0.000000s elapsed wall-clock time
% 
4

1 回答 1

0

示例代码已损坏:

#include <boost/timer/timer.hpp>
#include <cmath>

int main()
{
  boost::timer::auto_cpu_timer t;

  for (long i = 0; i < 100000000; ++i)
    std::sqrt(123.456L); // burn some time

  return 0;
}

std::sqrt函数是一个纯函数。也就是说,除了仅根据其参数返回值外,它没有其他影响。如果未使用该值,则可以丢弃函数调用。由于未使用返回值,因此可以跳过该函数。这导致代码根本不使用任何时间。

您可以通过以下方式修复它:

  long t = 0;
  for (long i = 0; i < 100000000; ++i)
    t += std::sqrt(123.456L + i); // burn some time
  std::cout << "t = " << t << std::endl;

现在,使用返回值,参数每次都不一样。这意味着该函数被重复调用,给你一些时间。

于 2012-08-09T01:01:44.463 回答