本文介绍了嵌入式系统时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在嵌入式系统(Raspberry Pi A +运行ArchLinux)上为传感器测量添加时间戳。我从 time.h
找到时间
,但它给了我第二的解决方案,我至少需要毫秒。
系统将运行几个小时,我不担心长时间漂移。
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\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
注意:
如果您想要更高的分辨率,您可以使用微秒
这样:
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
这篇关于嵌入式系统时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!