Python / C++ 中 time
库详解
时间函数在性能测试、调试日志和调度任务中非常常见。Python 和 C++ 都提供了时间相关的库,但在用法和单位上存在一些区别,本文将详细说明它们的使用方式和对比。
x Python 中的 time
模块
Python 提供了 time
模块,支持多种时间相关功能,下面是一些常见函数的说明:
常用函数对比表
函数 | 功能 | 返回单位 |
---|---|---|
time.time() | 返回当前时间戳(自1970年1月1日) | 秒(float ) |
time.sleep(secs) | 阻塞当前线程指定秒数 | 秒(float ) |
time.perf_counter() | 精确计时,包含系统睡眠时间,适合计时 | 秒(float ) |
time.process_time() | 只计算当前进程的CPU时间,不包含sleep | 秒(float ) |
time.strftime(fmt, t) | 格式化时间为字符串 | N/A |
time.strptime(str, fmt) | 将字符串解析为时间对象 | struct_time |
示例代码
import time
start = time.perf_counter()
time.sleep(1.5)
end = time.perf_counter()
print(f"程序耗时: {end - start:.3f} 秒")
C++ 中的 <ctime>
与 <chrono>
C++ 提供了两个时间相关的库:
<ctime>
:C 风格,简单但精度较低<chrono>
:C++11 引入,支持高精度计时
<ctime>
常用函数
函数 | 功能 | 返回单位 |
---|---|---|
time(nullptr) | 获取当前时间戳(从1970起) | 秒(time_t ) |
sleep(unsigned int seconds) | 休眠秒数(在 <unistd.h> 中) | 秒 |
difftime(t1, t2) | 计算两个 time_t 的差值 | 秒(double ) |
示例代码:
#include <ctime>
#include <iostream>
#include <unistd.h> // sleep()
int main() {
time_t start = time(nullptr);
sleep(2); // 休眠2秒
time_t end = time(nullptr);
std::cout << "耗时: " << difftime(end, start) << " 秒" << std::endl;
return 0;
}
<chrono>
高精度计时(推荐)
类型/函数 | 功能 | 单位 |
---|---|---|
std::chrono::high_resolution_clock | 高精度时钟 | 纳秒 / 毫秒等 |
std::this_thread::sleep_for() | 线程休眠 | 可指定时间单位(如毫秒、微秒等) |
示例代码:
#include <chrono>
#include <thread>
#include <iostream>
int main() {
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(1500)); // 睡眠1.5秒
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "程序耗时: " << duration.count() << " 毫秒" << std::endl;
return 0;
}
注意:duration_cast<>() 可用于转换时间单位(如微秒、毫秒、秒等)。
Python / C++ 获取当前时间
在模型训练过程中,我们需要记录log或者存储文件时,会添加当前的时间戳,为文件命名,以下是python和c++获取时间的方法。
Python
import time
from datetime import datetime
# 1. 当前时间戳(从1970年1月1日以来的秒数,float)
timestamp = time.time()
print("Timestamp:", timestamp) # 单位:秒
# 2. 当前时间字符串(本地时间)
now = time.localtime() # struct_time
print("Local time:", time.strftime("%Y-%m-%d %H:%M:%S", now))
# 3. 更方便的格式化(推荐)
dt = datetime.now()
print("Datetime:", dt.strftime("%Y-%m-%d %H:%M:%S"))
C++
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
int main() {
// 1. 获取当前系统时间点
auto now = std::chrono::system_clock::now();
// 2. 转换为 time_t(即时间戳)
std::time_t now_time_t = std::chrono::system_clock::to_time_t(now);
// 3. 格式化输出
std::cout << "Current Time: "
<< std::put_time(std::localtime(&now_time_t), "%Y-%m-%d %H:%M:%S")
<< std::endl;
return 0;
}