【问题标题】:Timestamps for embedded system嵌入式系统的时间戳
【发布时间】:2015-07-07 23:45:55
【问题描述】:

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

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

【问题讨论】:

  • 什么操作系统(如果有)?
  • 运行 ArchLinux 的树莓派 A+ (armv6)
  • 请将该信息添加到问题中。

标签: c++ timestamp


【解决方案1】:

如果您有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';
}

输出:

2015-07-08 10:13:29.930

注意:

如果你想要更高的分辨率,你可以像这样使用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();
}

输出:

2015-07-08 10:20:39.454163

【讨论】:

    【解决方案2】:

    C++11 chrono 头文件中有很多可用的功能,请参考这个给定的链接

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-05
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 2010-09-15
      • 1970-01-01
      相关资源
      最近更新 更多