我使用的是boost 1.46,它不包含boost::timer,我还能用什么方法对我的函数进行计时。
我目前正在这样做:
time_t now = time(0);
<some stuff>
time_t after = time(0);
cout << after - now << endl;
但它只在几秒钟内给出了答案,所以如果函数花费< 1s,它将显示0。
谢谢
发布于 2016-05-08 01:50:51
使用std::chrono
#include <chrono>
#include <thread>
#include <iostream>
// There are other clocks, but this is usually the one you want.
// It corresponds to CLOCK_MONOTONIC at the syscall level.
using Clock = std::chrono::steady_clock;
using std::chrono::time_point;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using namespace std::literals::chrono_literals;
using std::this_thread::sleep_for;
int main()
{
time_point<Clock> start = Clock::now();
sleep_for(500ms);
time_point<Clock> end = Clock::now();
milliseconds diff = duration_cast<milliseconds>(end - start);
std::cout << diff.count() << "ms" << std::endl;
}
std::chrono
为C++11,std::literals
为C++14 (否则需要milliseconds(500)
)。
发布于 2013-02-26 23:25:19
原来boost 1.46中有一个版本的时间(只是在不同的位置)。感谢@jogojapan指出这一点。
可以这样做:
#include <boost/timer.hpp>
timer t;
<some stuff>
std::cout << t.elapsed() << std::endl;
或者像@Quentin Perez指出的那样使用std库(我会接受最初提出的要求)
发布于 2016-01-06 05:15:58
基于Quentin Perez的解决方案,您可以使用std::function和lambda将任意函数传递给time。
#include <ctime>
#include <iostream>
#include <functional>
void timeit(std::function<void()> func) {
std::clock_t start = std::clock();
func();
int ms = (std::clock() - start) / (double) (CLOCKS_PER_SEC / 1000);
std::cout << "Finished in " << ms << "ms" << std::endl;
}
int main() {
timeit([] {
for (int i = 0; i < 10; ++i) {
std::cout << "i = " << i << std::endl;
}
});
return 0;
}
https://stackoverflow.com/questions/15092504
复制相似问题