C++ 获取毫秒时间

c++ get millsecond time

我想获取秒后包含六位数字的日期和时间,例如2017-07-03 15:01:01.123456。如何获得?我尝试使用 time timeval 和 gettimeofday,但出现错误。 我的代码:

time_t timer;
char timestr[29];
struct timeval *tm_info;

time(&timer);

tm_info = gettimeofday(&timer);

strftime(timestr, 29, "%Y-%m-%d %H:%M:%S", tm_info);

ss << timestr;

首先,如果你想要当前秒的小数点后六位分辨率,我们说的是微秒 (1us = 10E-6),而不是毫秒 (1ms = 10E-3)。此外,您可能应该使用 std::chrono,因为 gettimeofday() 是 OS 特定于 Linux,并且不会在其他系统上工作。

要获取日期,您可以使用 <time.h> 及其 gmtime() (UTC),其中 returns 和 struct tm。至于时间,一个简单的方法来获得当前秒后经过的时间,以微秒为单位(例如 14:31:09.590721),是利用 time_t 的分辨率仅为 1s 的事实:

#include <iostream>
#include <string>
#include <chrono>
#include <time.h>

int main() {
    for (int i = 0; i < 1000; ++i) {
        auto now = std::chrono::system_clock::now();
        auto now_t = std::chrono::system_clock::to_time_t(now);

        //Exploit now_t (time_t): resolution is only 1 second - get microseconds
        auto dur = now - std::chrono::system_clock::from_time_t(now_t);
        auto micros = std::chrono::duration_cast<std::chrono::microseconds>(dur).count();


        //Print the date and time as yyyy-mm-dd hh::mm::ss.xxxxxx
        tm& now_tm = *(gmtime(&now_t));
        std::string year = std::to_string(now_tm.tm_year + 1900) + "-";
        std::string mon = std::to_string(now_tm.tm_mon + 1) + "-";
        std::string day = std::to_string(now_tm.tm_mday) + " ";
        std::string hour = std::to_string(now_tm.tm_hour);
        std::string min = std::to_string(now_tm.tm_min);
        std::string sec = std::to_string(now_tm.tm_sec);

        if (hour.size() == 1) hour.insert(0, "0");
        if (min.size() == 1) min.insert(0, "0");
        if (sec.size() == 1) sec.insert(0, "0");

        std::cout << year << mon << day
            << hour << ":" << min << ":" << sec << "." << micros << "\n";
    }
    return 1;
}

运行 我所在时区的 10 次迭代给出:

2018-5-4 12:36:11.47578
2018-5-4 12:36:11.48663
2018-5-4 12:36:11.49516
2018-5-4 12:36:11.50392
2018-5-4 12:36:11.51261
2018-5-4 12:36:11.52455
2018-5-4 12:36:11.53316
2018-5-4 12:36:11.54213
2018-5-4 12:36:11.55113
2018-5-4 12:36:11.55969

PS:当你处于这种粒度时,你应该知道时钟源精度/漂移。这取决于系统(硬件、OS 等)。严格的计时需要特殊的硬件(例如 GPSDO)和软件。

这里有一个使用 <chrono>Howard Hinnant's date/time library 的更简单的方法。这将打印出当前时间 UTC 到微秒精度十次:

#include "date/date.h"
#include <iostream>

int
main()
{
    using namespace std::chrono;
    using namespace date;
    for (auto i = 0; i < 10; ++i)
        std::cout << floor<microseconds>(system_clock::now()) << '\n';
}

示例输出:

2018-05-04 14:01:04.473663
2018-05-04 14:01:04.473770
2018-05-04 14:01:04.473787
2018-05-04 14:01:04.473805
2018-05-04 14:01:04.473824
2018-05-04 14:01:04.473842
2018-05-04 14:01:04.473860
2018-05-04 14:01:04.473878
2018-05-04 14:01:04.473895
2018-05-04 14:01:04.473914