以毫秒为单位捕获时间

ron*_*nan 12 c++ stl resolution timer

以下代码用于在日志中打印时间:

#define PRINTTIME() struct tm  * tmptime;
time_t     tmpGetTime;
time(&tmpGetTime);
tmptime = localtime(&tmpGetTime);
cout << tmptime->tm_mday << "/" <<tmptime->tm_mon+1 << "/" << 1900+tmptime->tm_year << " " << tmptime->tm_hour << ":" << tmptime->tm_min << ":" << tmptime->tm_sec<<">>";
Run Code Online (Sandbox Code Playgroud)

有没有办法为此添加毫秒?

neu*_*uro 21

要具有毫秒级的精度,您必须使用特定于您的操作系统的系统调用.

在Linux中你可以使用

#include <sys/time.h>

timeval tv;
gettimeofday(&tv, 0);
// then convert struct tv to your needed ms precision
Run Code Online (Sandbox Code Playgroud)

timeval 具有微秒精度.

在Windows中,您可以使用:

#include <Windows.h>

SYSTEMTIME st;
GetSystemTime(&st);
// then convert st to your precision needs
Run Code Online (Sandbox Code Playgroud)

当然你可以使用Boost为你做这件事:)


use*_*106 16

// C++ 11风格:

cout << "Time in Milliseconds =" << 
 chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count() 
 << std::endl;

cout << "Time in MicroSeconds=" << 
 chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count() 
 << std::endl;
Run Code Online (Sandbox Code Playgroud)