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

Aly*_*Aly 26 c++ boost timer timing std

我正在使用boost 1.46,它不包括boost :: timer,还有什么方法可以计算我的功能.

我目前正在这样做:

time_t now = time(0);
<some stuff>
time_t after = time(0);

cout << after - now << endl; 
Run Code Online (Sandbox Code Playgroud)

但它只是在几秒钟内给出答案,所以如果函数小于1,则显示0.

谢谢

Que*_*rez 29

在linux或Windows中:

#include <ctime>
#include <iostream>

int
main(int, const char**)
{
     std::clock_t    start;

     start = std::clock();
     // your test
     std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
     return 0;
}
Run Code Online (Sandbox Code Playgroud)

祝好运 ;)

  • 请注意,这会测量CPU时间,而不是经过的时间.例如,如果函数休眠,则不会测量. (20认同)
  • 那是CPU时间,sleep或者多线程的时候会有问题 (2认同)

o11*_*11c 23

使用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;
}
Run Code Online (Sandbox Code Playgroud)

std::chrono是C++ 11,std::literals是C++ 14(否则你需要milliseconds(500)).


Aly*_*Aly 9

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

它可以这样做:

#include <boost/timer.hpp>

timer t;
<some stuff>
std::cout << t.elapsed() << std::endl;
Run Code Online (Sandbox Code Playgroud)

或者使用std libs作为@Quentin Perez指出(我会接受最初的问题)

  • 问题标题说'没有`boost :: timer`' (7认同)
  • @Progo更具体地说,问题是使用boost 1.46是可以的.(请注意,这个答案由原问题的作者给出) (6认同)