c++ - 以毫秒为单位捕获时间

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

#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<<">>";

有没有办法增加毫秒数?


最佳答案:

要获得毫秒精度,您必须使用特定于操作系统的系统调用。
在Linux中,您可以使用

#include <sys/time.h>

timeval tv;
gettimeofday(&tv, 0);
// then convert struct tv to your needed ms precision

timeval具有微秒精度。
在Windows中,您可以使用:
#include <Windows.h>

SYSTEMTIME st;
GetSystemTime(&st);
// then convert st to your precision needs

当然,您可以使用Boost为您完成这项工作:)