首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在没有boost::timer的情况下以毫秒为单位对函数计时

如何在没有boost::timer的情况下以毫秒为单位对函数计时
EN

Stack Overflow用户
提问于 2013-02-26 23:08:43
回答 4查看 75.7K关注 0票数 28

我使用的是boost 1.46,它不包含boost::timer,我还能用什么方法对我的函数进行计时。

我目前正在这样做:

代码语言:javascript
复制
time_t now = time(0);
<some stuff>
time_t after = time(0);

cout << after - now << endl; 

但它只在几秒钟内给出了答案,所以如果函数花费< 1s,它将显示0。

谢谢

EN

回答 4

Stack Overflow用户

发布于 2016-05-08 01:50:51

使用std::chrono

代码语言:javascript
复制
#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))。

票数 27
EN

Stack Overflow用户

发布于 2013-02-26 23:25:19

原来boost 1.46中有一个版本的时间(只是在不同的位置)。感谢@jogojapan指出这一点。

可以这样做:

代码语言:javascript
复制
#include <boost/timer.hpp>

timer t;
<some stuff>
std::cout << t.elapsed() << std::endl;

或者像@Quentin Perez指出的那样使用std库(我会接受最初提出的要求)

票数 9
EN

Stack Overflow用户

发布于 2016-01-06 05:15:58

基于Quentin Perez的解决方案,您可以使用std::function和lambda将任意函数传递给time。

代码语言:javascript
复制
#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;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15092504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档