gpt4 book ai didi

c++ - Boost:以秒/毫/微/纳计算函数运行的时间

转载 作者:太空狗 更新时间:2023-10-29 23:00:35 24 4
gpt4 key购买 nike

我基本上有一个学校项目来测试不同排序算法所花费的时间,并记录它们对 n 个数字进行排序所花费的时间。所以我决定使用带有 C++ 的 Boost 库来记录时间。我现在不知道该怎么做,我用谷歌搜索了一下,发现人们使用不同的方法。例如

auto start = boost::chrono::high_resolution_clock::now();
auto end = boost::chrono::high_resolution_clock::now();
auto time = (end-start).count();

boost::chrono::system_clock::now();

boost::chrono::steady_clock::now() 

甚至使用这样的东西

boost::timer::cpu_timer and boost::timer::auto_cpu_time

boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time( );

所以我想确定现在该怎么做,这就是我所拥有的

typedef boost::chrono::duration<double, boost::nano> boost_nano;

auto start_t = boost::chrono::high_resolution_clock::now();
// call function
auto end_t = boost::chrono::high_resolution_clock::now();
boost_nano time = (end_t - start_t);
cout << t.count();

那么我走在正确的轨道上吗?

最佳答案

您可能需要高分辨率计时器。

您可以使用 boost::chronostd::chrono

Boost Chrono 对内置 IO 有一些支持,因此它可以更轻松地以人性化的方式报告时间。

我通常使用类似这样的包装器:

template <typename Caption, typename F>
auto timed(Caption const& task, F&& f) {
using namespace boost::chrono;
struct _ {
high_resolution_clock::time_point s;
Caption const& task;
~_() { std::cout << " -- (" << task << " completed in " << duration_cast<milliseconds>(high_resolution_clock::now() - s) << ")\n"; }
} timing { high_resolution_clock::now(), task };

return f();
}

报告以毫秒为单位的时间。

这里的好处是你可以计时构造和类似的:

std::vector<int> large = timed("generate data", [] {
return generate_uniform_random_data(); });

还有,通用代码块:

timed("do_step2", [] {
// step two is foo and bar:
foo();
bar();
});

它可以工作,例如foo() 抛出,就好了。

演示

Live On Coliru

int main() {
return timed("demo task", [] {
sleep(1);
return 42;
});
}

打印

 -- (demo task completed in 1000 milliseconds)
42

关于c++ - Boost:以秒/毫/微/纳计算函数运行的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33405255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com