Timestamps for embedded system

前端 未结 2 886
遥遥无期
遥遥无期 2020-12-04 00:53

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 i

相关标签:
2条回答
  • 2020-12-04 01:23

    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\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:

    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
    
    0 讨论(0)
  • 2020-12-04 01:29

    There are a bunch of features available in C++11 chrono header file, please refer this given link

    0 讨论(0)
提交回复
热议问题