c ++获得毫秒时间

时间:2018-05-04 10:11:56

标签: c++ networking time packet

我希望在一秒钟之后得到包含六位数的日期和时间,例如2017-07-03 15:01:01.123456。怎么弄?我尝试使用timevalval和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;

2 个答案:

答案 0 :(得分:2)

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

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

#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:当你处于这种粒度时,应该知道时钟源精度/漂移。这取决于系统(hw,OS等)。严肃的计时需要特殊的硬件(例如GPSDO)和软件。

答案 1 :(得分:1)

使用<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