阅读量:101
在C++中获取精确的时间戳可以使用以下几种方法:
- 使用标准库函数time()获取当前时间戳,但该方法只能精确到秒级别。
#include
#include
int main() {
time_t now = time(0);
std::cout << "Current timestamp: " << now class="hljs-keyword">return 0;
}
- 使用C++11引入的std::chrono库获取更精确的时间戳,可以精确到纳秒级别。
#include
#include
int main() {
auto now = std::chrono::system_clock::now().time_since_epoch();
std::chrono::nanoseconds ns = std::chrono::duration_cast(now);
std::cout << "Current timestamp: " << ns class="hljs-built_in">count() << " nanoseconds since epoch" << std class="hljs-keyword">return 0;
}
以上两种方法都可以获取当前时间戳,根据需求选择合适的方法即可。