C++ 以毫秒为单位捕获时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1120478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capturing a time in milliseconds
提问by ronan
The following piece of code is used to print the time in the logs:
以下代码用于打印日志中的时间:
#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<<">>";
Is there any way to add milliseconds to this?
有什么办法可以增加毫秒数吗?
回答by neuro
To have millisecond precision you have to use system calls specific to your OS.
要获得毫秒精度,您必须使用特定于您的操作系统的系统调用。
In Linux you can use
在 Linux 中,您可以使用
#include <sys/time.h>
timeval tv;
gettimeofday(&tv, 0);
// then convert struct tv to your needed ms precision
timeval
has microsecond precision.
timeval
具有微秒精度。
In Windows you can use:
在 Windows 中,您可以使用:
#include <Windows.h>
SYSTEMTIME st;
GetSystemTime(&st);
// then convert st to your precision needs
Of course you can use Boostto do that for you :)
当然,您可以使用Boost为您做到这一点:)
回答by user3762106
//C++11 Style:
// 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;
回答by Chris Ballance
You need a timer with a higher resolution in order to capture milliseconds. Try this:
你需要一个更高分辨率的计时器来捕捉毫秒。尝试这个:
int cloc = clock();
//do something that takes a few milliseconds
cout << (clock() - cloc) << endl;
This is of course dependent on your OS.
这当然取决于您的操作系统。
回答by Eric
The high resolution timers are usually gettimeofday on Linux style platforms and QueryPerformanceCounter on Windows.
高分辨率计时器在 Linux 风格平台上通常是 gettimeofday,在 Windows 上通常是 QueryPerformanceCounter。
You should be aware that timing the duration of a single operation (even with a high resolution timer) will not yield accurate results. There are too many random factors at play. To get reliable timing information, you should run the task to be timed in a loop and compute the average task time. For this type of timing, the clock() function should be sufficient.
您应该意识到对单个操作的持续时间进行计时(即使使用高分辨率计时器)不会产生准确的结果。有太多随机因素在起作用。要获得可靠的计时信息,您应该循环运行要计时的任务并计算平均任务时间。对于这种类型的计时,clock() 函数应该足够了。
回答by Yuval Baror
If you don't want to use any OS-specific code, you can use the ACE package which supplies the ACE_OS::gettimeofday
function for most standard operating systems.
For example:
如果您不想使用任何特定于操作系统的代码,您可以使用ACE_OS::gettimeofday
为大多数标准操作系统提供该功能的 ACE 包。例如:
ACE_Time_Value startTime = ACE_OS::gettimeofday();
do_something();
ACE_Time_Value endTime = ACE_OS::gettimeofday();
cout << "Elapsed time: " << (endTime.sec() - startTime.sec()) << " seconds and " << double(endTime.usec() - startTime.usec()) / 1000 << " milliseconds." << endl;
This code will work regardless of your OS (as long as ACE supports this OS).
无论您的操作系统如何(只要 ACE 支持此操作系统),此代码都将起作用。
回答by MauriRamone
In Ubuntu 16.04 this worked for me...
在 Ubuntu 16.04 中,这对我有用...
const std::string currentDateTime() {
char fmt[64], buf[64];
struct timeval tv;
struct tm *tm;
gettimeofday(&tv, NULL);
tm = localtime(&tv.tv_sec);
strftime(fmt, sizeof fmt, "%Y-%m-%d %H:%M:%S.%%06u", tm);
snprintf(buf, sizeof buf, fmt, tv.tv_usec);
return buf;
}
Then, with...
然后,与...
std::cout << currentDateTime();
I get...
我得到...
2016-12-29 11:09:55.331008
回答by Howard Hinnant
New answer for old question using C++11 or C++14 and this free, open-source library:
旧问题的新答案使用 C++11 或 C++14 和这个免费的开源库:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
auto now = make_zoned(current_zone(), floor<milliseconds>(system_clock::now()));
cout << format("%e/%m/%Y %T", now) << '\n';
}
This just output for me:
这只是对我的输出:
16/01/2017 15:34:32.167
which is my current local date and time to millisecond precision. By eliminating the floor<milliseconds>()
you will automatically get whatever precision your system_clock
has.
这是我当前的本地日期和时间到毫秒精度。通过消除 ,floor<milliseconds>()
您将自动获得您system_clock
拥有的任何精度。
If you wanted the result as a UTC timestamp instead of a local timestamp, it is even easier:
如果您希望将结果作为 UTC 时间戳而不是本地时间戳,则更简单:
auto now = floor<milliseconds>(system_clock::now());
cout << format("%e/%m/%Y %T", now) << '\n';
And if you want a UTC timestamp and you aren't picky about the precision or the format, you can just:
如果你想要一个 UTC 时间戳并且你对精度或格式不挑剔,你可以:
cout << system_clock::now() << '\n';
which just output for me:
这只是为我输出:
2017-01-16 20:42:11.267245