Python / C++ 中 `time` 库详解

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值