C++11 chrono 类型仅使用一个数字来表示自给定 Epoch 以来的时间,这与使用两个数字来精确表示时间的timeval
(or ) 结构不同。timespec
因此,对于 C++11 chrono,您不需要该combine()
方法。
返回的时间戳的内容now()
取决于你使用的时钟;有树时钟,在http://en.cppreference.com/w/cpp/chrono中描述:
system_clock wall clock time from the system-wide realtime clock
steady_clock monotonic clock that will never be adjusted
high_resolution_clock the clock with the shortest tick period available
如果您希望连续的时间戳始终不同,请使用稳定时钟:
auto t1 = std::chrono::steady_clock::now();
...
auto t2 = std::chrono::steady_clock::now();
assert (t2 > t1);
编辑:回复评论
#include <iostream>
#include <chrono>
#include <cstdint>
int main()
{
typedef std::chrono::duration< uint32_t, std::ratio<1> > s32_t;
typedef std::chrono::duration< uint32_t, std::milli > ms32_t;
s32_t first_part;
ms32_t second_part;
auto t1 = std::chrono::nanoseconds( 2500000000 ); // 2.5 secs
first_part = std::chrono::duration_cast<s32_t>(t1);
second_part = std::chrono::duration_cast<ms32_t>(t1-first_part);
std::cout << "first part = " << first_part.count() << " s\n"
<< "seconds part = " << second_part.count() << " ms" << std::endl;
auto t2 = std::chrono::nanoseconds( 2800000000 ); // 2.8 secs
first_part = std::chrono::duration_cast<s32_t>(t2);
second_part = std::chrono::duration_cast<ms32_t>(t2-first_part);
std::cout << "first part = " << first_part.count() << " s\n"
<< "seconds part = " << second_part.count() << " ms" << std::endl;
}
输出:
first part = 2 s
seconds part = 500 ms
first part = 2 s
seconds part = 800 ms