c++获取系统时间
时间: 2025-05-22 22:47:33 浏览: 11
在C++中获取系统时间可以通过多种方式实现,最常见的是使用 `<ctime>` 或 `<chrono>` 库。以下是两种方法的示例代码:
### 方法一:使用 `<ctime>` 获取系统时间
```cpp
#include <iostream>
#include <ctime>
void getCurrentTimeUsingCtime() {
std::time_t now = std::time(nullptr); // 获取当前时间戳
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", std::localtime(&now)); // 格式化时间
std::cout << "当前时间(ctime): " << buffer << std::endl;
}
int main() {
getCurrentTimeUsingCtime();
return 0;
}
```
**解释**:
- `std::time(nullptr)` 返回当前的日历时间(以秒为单位,自1970年1月1日以来)。
- `std::localtime(&now)` 将时间转换为本地时间结构体 `tm`。
- `std::strftime` 将时间格式化为字符串。
---
### 方法二:使用 `<chrono>` 获取高精度系统时间
```cpp
#include <iostream>
#include <chrono>
#include <ctime>
void getCurrentTimeUsingChrono() {
auto now = std::chrono::system_clock::now(); // 获取当前时间点
std::time_t now_time = std::chrono::system_clock::to_time_t(now); // 转换为time_t类型
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", std::localtime(&now_time));
std::cout << "当前时间(chrono): " << buffer << std::endl;
}
int main() {
getCurrentTimeUsingChrono();
return 0;
}
```
**解释**:
- `std::chrono::system_clock::now()` 获取当前时间点(高精度)。
- `std::chrono::system_clock::to_time_t()` 将高精度时间点转换为传统的 `time_t` 类型。
- 其余步骤与 `<ctime>` 示例相同。
---
### 总结
- 如果只需要普通精度的时间,可以使用 `<ctime>`。
- 如果需要更高精度的时间(例如微秒级别),推荐使用 `<chrono>`。
阅读全文
相关推荐















