[英]Get current time in milliseconds using C++ and Boost
在我的線程中(使用 boost::thread)我需要以 ms 或更短的時間檢索當前時間並轉換為 ms:
實際上,在這里閱讀我發現了這一點:
tick = boost::posix_time::second_clock::local_time();
now = boost::posix_time::second_clock::local_time();
並且似乎有效,但是在我需要一個很長的毫秒值之后......
我該怎么做?
您可以使用boost::posix_time::time_duration
來獲取時間范圍。 比如像這樣
boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();
為了獲得更高的分辨率,您可以更改您正在使用的時鍾。 例如boost::posix_time::microsec_clock
,盡管這可能取決於操作系統。 例如,在 Windows 上, boost::posix_time::microsecond_clock
具有毫秒分辨率,而不是微秒。
一個有點依賴於硬件的例子。
int main(int argc, char* argv[])
{
boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();
boost::posix_time::time_duration diff = t2 - t1;
std::cout << diff.total_milliseconds() << std::endl;
boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration msdiff = mst2 - mst1;
std::cout << msdiff.total_milliseconds() << std::endl;
return 0;
}
在我的win7機器上。 第一個輸出是 0 或 1000。第二個分辨率。 第二個幾乎總是 500,因為時鍾的分辨率更高。 我希望能有所幫助。
如果您的意思是自紀元以來的毫秒數,您可以這樣做
ptime time_t_epoch(date(1970,1,1));
ptime now = microsec_clock::local_time();
time_duration diff = now - time_t_epoch;
x = diff.total_milliseconds();
但是,目前還不清楚你在追求什么。
查看文檔中 DateTime at Boost Date Time的示例
// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;
int main()
{
pt::ptime current_date_microseconds = pt::microsec_clock::local_time();
long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();
pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);
pt::ptime current_date_milliseconds(current_date_microseconds.date(),
current_time_milliseconds);
std::cout << "Microseconds: " << current_date_microseconds
<< " Milliseconds: " << current_date_milliseconds << std::endl;
// Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}
試試這個:前面提到的 import headers .. 只給出秒和毫秒。 如果您需要解釋代碼,請閱讀此鏈接。
#include <windows.h>
#include <stdio.h>
void main()
{
SYSTEMTIME st;
SYSTEMTIME lt;
GetSystemTime(&st);
// GetLocalTime(<);
printf("The system time is: %02d:%03d\n", st.wSecond, st.wMilliseconds);
// printf("The local time is: %02d:%03d\n", lt.wSecond, lt.wMilliseconds);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.