插件窝 干货文章 linux有计算时间的函数吗

linux有计算时间的函数吗

时间 clock time 纳秒 763    来源:    2025-04-29

在Linux系统中,可以通过多种方式计算时间,包括C/C++标准库函数、系统调用和命令行工具。以下是详细的分类说明:


1. C/C++标准库函数

1.1 时间获取

  • time()
    返回从1970-01-01 00:00:00 UTC(Epoch时间)至今的秒数(time_t类型):

    #include <time.h>
    time_t now = time(NULL);
    
  • gettimeofday()
    获取微秒级精度的时间(已废弃,建议改用clock_gettime):

    #include <sys/time.h>
    struct timeval tv;
    gettimeofday(&tv, NULL);  // tv.tv_sec (秒) + tv.tv_usec (微秒)
    
  • clock_gettime()
    高精度时间(纳秒级),支持多种时钟源(如系统实时时钟、单调时钟等):

    #include <time.h>
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);  // ts.tv_sec (秒) + ts.tv_nsec (纳秒)
    

1.2 时间格式化

  • strftime()
    将时间转换为可读字符串: c char buf[64]; time_t now = time(NULL); strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", localtime(&now));

1.3 耗时计算

  • clock()
    返回程序运行的CPU时间(时钟滴答数): c clock_t start = clock(); // ... 执行代码 ... double cpu_time = (double)(clock() - start) / CLOCKS_PER_SEC;

2. 系统调用

  • times()
    获取进程及其子进程的CPU时间(用户态/内核态):

    #include <sys/times.h>
    struct tms buf;
    times(&buf);  // buf.tms_utime (用户态时间)
    
  • nanosleep()
    高精度睡眠(纳秒级):

    struct timespec delay = {1, 500000000}; // 1.5秒
    nanosleep(&delay, NULL);
    

3. 命令行工具

  • date
    显示或设置系统时间:

    date +"%Y-%m-%d %H:%M:%S"  # 输出:2023-10-01 14:30:00
    
  • time
    测量命令执行时间:

    time ls -l  # 输出real/user/sys时间
    
  • uptime
    显示系统运行时间:

    uptime  # 输出:14:30:00 up 10 days,  2:30,  users...
    

4. 高精度计时示例(C++11及以上)

#include <chrono>
auto start = std::chrono::high_resolution_clock::now();
// ... 执行代码 ...
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;

5. 关键注意事项

  • 单调时钟(Monotonic Clock)
    使用CLOCK_MONOTONIC避免系统时间跳变的影响(适合计时场景):

    clock_gettime(CLOCK_MONOTONIC, &ts);
    
  • 时区处理
    使用localtime_r(线程安全)或setenv("TZ", "UTC", 1)修改时区。

  • 性能分析工具
    复杂场景可结合perfstracegprof进行更深入的分析。


根据具体需求选择合适的函数:
- 简单计时time()std::chrono
- 高精度clock_gettime()
- 跨平台 → C++11的<chrono>
- 命令行date/time命令