linux c++ 获取系统时间
时间: 2024-07-15 13:01:28 浏览: 159
在Linux环境下使用C++获取系统当前时间,你可以利用标准库中的<ctime>和<chrono>头文件,以及相关的日期/时间处理功能。这里是一个简单的示例:
```cpp
#include <iostream>
#include <chrono>
#include <ctime>
int main() {
// 获取当前时间
std::time_t now = std::time(nullptr); // 使用std::time获取当前时间戳
// 将时间戳转换为tm结构体(包含年、月、日等信息)
std::tm local_time = *std::localtime(&now);
// 输出格式化的时间
std::cout << "Current time (local): " << std::put_time(&local_time, "%Y-%m-%d %H:%M:%S") << '\n';
// 如果你需要高精度的时间,可以使用std::chrono库
auto high_resolution_clock = std::chrono::high_resolution_clock();
auto current_time = high_resolution_clock.now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(current_time.time_since_epoch());
std::cout << "Current time (high precision): " << duration.count() << " seconds since epoch\n";
return 0;
}
```
这段代码首先获取了系统的当前时间戳(`std::time(nullptr)`),然后将其转换成`tm`结构体以便格式化输出。如果需要更高精度的时间,比如纳秒级别的,就使用了`std::chrono::high_resolution_clock`。
阅读全文
相关推荐

















