嵌入式系统的时间戳

2022-01-13 00:00:00 timestamp c++

我想在嵌入式系统(运行 ArchLinux 的 Raspberry Pi A+)上为传感器测量添加时间戳.我从 time.h 中找到了 time 但它给了我秒"的分辨率,我至少需要毫秒".系统会运行几个小时,我不担心长时间漂移.

I would like to add timestamps to sensor measurements on an embedded system (Raspberry Pi A+ running ArchLinux). I've found time from time.h but it gives me "second" resolution and I would need at least "milliseconds". The system would run for a few hours, I'm not concerned about long duration drifts.

我如何在 C++ 中得到它?

How could I get that in C++?

推荐答案

如果你有 C++11 你可以使用 <chrono><ctime> 库像这样:

If you have C++11 you can use the <chrono> and <ctime> library like this:

#include <ctime>
#include <string>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <iostream>

// use strftime to format time_t into a "date time"
std::string date_time(std::time_t posix)
{
    char buf[20]; // big enough for 2015-07-08 10:06:51
    std::tm tp = *std::localtime(&posix);
    return {buf, std::strftime(buf, sizeof(buf), "%F %T", &tp)};
}

std::string stamp()
{
    using namespace std;
    using namespace std::chrono;

    // get absolute wall time
    auto now = system_clock::now();

    // find the number of milliseconds
    auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;

    // build output string
    std::ostringstream oss;
    oss.fill('0');

    // convert absolute time to time_t seconds
    // and convert to "date time"
    oss << date_time(system_clock::to_time_t(now));
    oss << '.' << setw(3) << ms.count();

    return oss.str();
}

int main()
{
    std::cout << stamp() << '
';
}

输出:

2015-07-08 10:13:29.930

注意:

如果你想要更高的分辨率,你可以像这样使用 microseconds:

If you want higher resolution you can use microseconds like this:

std::string stamp()
{
    using namespace std;
    using namespace std::chrono;

    auto now = system_clock::now();

    // use microseconds % 1000000 now
    auto us = duration_cast<microseconds>(now.time_since_epoch()) % 1000000;

    std::ostringstream oss;
    oss.fill('0');

    oss << date_time(system_clock::to_time_t(now));
    oss << '.' << setw(6) << us.count();

    return oss.str();
}

输出:

2015-07-08 10:20:39.454163

相关文章