我正在尝试使用Boost.Chrono来测量代码的CPU时间。我的C ++代码如下所示。问题是我有时会得到负的持续时间作为输出。当我使用" process_real_cpu_clock"时会发生这种情况。当我使用" steady_clock"问题没有出现。我采取的一些产出如下:
第一次实施的时间:360毫秒
第二次实施的时间:-3284.97 ms
第一次实施的时间:360毫秒
第二次实施的时间:1010毫秒
第一次实施的时间:-3924.97 ms
第二次实施的时间:1010毫秒
只有第二个符合预期。我想这个问题是关于持续时间的溢出,但是在第三个输出中,第一个实现的时间应该是第二个实现的时间的1/3,那么如果我能看到第二个实现的时间,那么不应该有溢出。 (我正在使用Boost 1.54,并在VirtualBox上使用Ubuntu)
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <boost/chrono.hpp>
#include <boost/chrono/process_cpu_clocks.hpp>
int main() {
int x,y,result,runs;
srand(time(NULL));
runs=1e7;
boost::chrono::process_real_cpu_clock::time_point start, start2;
boost::chrono::process_real_cpu_clock::time_point end, end2;
start= boost::chrono::process_real_cpu_clock::now();
for (int i=0;i<runs;i++) {
x=rand() %100 +1;
y=rand() %100 +1;
auto dummy=x*y;
result=(result+dummy)%50;
}
end=boost::chrono::process_real_cpu_clock::now();
boost::chrono::process_real_cpu_clock::duration diff=end-start;
start2= boost::chrono::process_real_cpu_clock::now();
for (int i=0;i<(3*runs);i++) {
x=rand() %100 +1;
y=rand() %100 +1;
auto dummy=x*y;
result=(result+dummy)%50;
}
end2=boost::chrono::process_real_cpu_clock::now();
boost::chrono::process_real_cpu_clock::duration diff2=end2-start2;
std::cout << "time for 1st implemention:"<<boost::chrono::duration <double, boost::milli> (diff).count()<< " ns" << std::endl;
std::cout << "time for 2nd implementation:"<<boost::chrono::duration <double, boost::milli> (diff2).count()<< " ns" << std::endl;
return 0;
}
答案 0 :(得分:1)
我怀疑你错误地使用了boost::milli
(这只是Boost Ratio
的通用比率)。
您希望将duration_cast
与chrono中的单位一起使用:
std::cout << "time for 1st implemention:" << duration_cast<nanoseconds>(diff).count() << " ns\n";
std::cout << "time for 2nd implementation:" << duration_cast<nanoseconds>(diff2).count() << " ns\n";
这是我对它的看法(为可读性选择毫秒):
<强> Live On Coliru 强>
#include <iostream>
#include <boost/chrono.hpp>
#include <boost/chrono/process_cpu_clocks.hpp>
using namespace boost::chrono;
template <typename R, typename P>
static std::ostream& operator<<(std::ostream& os, duration<R,P> const& d) {
return os << boost::chrono::duration_cast<boost::chrono::milliseconds>(d).count() << "ms";
}
template <typename Clock = boost::chrono::process_cpu_clock, typename F, typename... Args>
nanoseconds bench(F&& f, Args&&... args) {
auto start = Clock::now();
volatile auto force = std::forward<F>(f)(std::forward<Args>(args)...);
(void) force;
return Clock::now() - start;
}
long long foo(int runs) {
long long result = 0;
for (int i = 0; i < runs; i++) {
int x = rand() % 100 + 1;
int y = rand() % 100 + 1;
auto dummy = x * y;
result = (result + dummy) % 50;
}
return result;
}
int main() {
srand(time(NULL));
std::cout << "1st method: " << bench(foo, 1e7) << "\n";
std::cout << "2nd method: " << bench(foo, 3e7) << "\n";
}
打印
1st method: 340ms
2nd method: 1010ms