简体   繁体   English

嵌入式系统的时间戳

[英]Timestamps for embedded system

I would like to add timestamps to sensor measurements on an embedded system (Raspberry Pi A+ running ArchLinux). 我想在嵌入式系统(运行ArchLinux的Raspberry Pi A +)上为传感器测量添加时间戳。 I've found time from time.h but it gives me "second" resolution and I would need at least "milliseconds". 我从time.h找到了time ,但是它给了我“秒”的分辨率,我至少需要“毫秒”。 The system would run for a few hours, I'm not concerned about long duration drifts. 该系统将运行几个小时,我不担心长时间漂移。

How could I get that in C++? 我怎么能用C ++做到这一点?

If you have C++11 you can use the <chrono> and <ctime> library like this: 如果您具有C++11 ,则可以使用<chrono><ctime>库,如下所示:

#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\0
    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() << '\n';
}

Output: 输出:

2015-07-08 10:13:29.930

Note: 注意:

If you want higher resolution you can use microseconds like this: 如果需要更高的分辨率,可以使用以下microseconds

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();
}

Output: 输出:

2015-07-08 10:20:39.454163

C ++ 11 chrono头文件中有很多功能,请参考此给定链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM