插件窝 干货文章 linux有获取时间的函数吗

linux有获取时间的函数吗

time clock include 时间 435    来源:    2025-05-03

在 Linux 系统中,获取时间的函数有多种,适用于不同场景和精度需求。以下是常用的时间获取函数分类及示例:


1. 秒级精度(时间戳/日历时间)

time()

  • 头文件: <time.h>
  • 返回值: 自 1970-01-01 00:00:00 UTC 以来的秒数(time_t 类型)。
  • 示例

    #include <time.h>
    #include <stdio.h>
    
    int main() {
      time_t current_time = time(NULL);
      printf("Timestamp: %ld\n", current_time);
      return 0;
    }
    

gettimeofday()(微秒级精度,已废弃但广泛使用)

  • 头文件: <sys/time.h>
  • 返回值: 结构体 struct timeval,包含秒和微秒。
  • 示例

    #include <sys/time.h>
    #include <stdio.h>
    
    int main() {
      struct timeval tv;
      gettimeofday(&tv, NULL);
      printf("Seconds: %ld, Microseconds: %ld\n", tv.tv_sec, tv.tv_usec);
      return 0;
    }
    

    注意:在较新的系统中推荐使用 clock_gettime() 替代。


2. 纳秒级精度

clock_gettime()

  • 头文件: <time.h>
  • 时钟类型
    • CLOCK_REALTIME:系统实时时间(可受用户修改影响)。
    • CLOCK_MONOTONIC:单调时间,从系统启动开始计算(不受时间修改影响)。
  • 示例

    #include <time.h>
    #include <stdio.h>
    
    int main() {
      struct timespec ts;
      clock_gettime(CLOCK_REALTIME, &ts);
      printf("Seconds: %ld, Nanoseconds: %ld\n", ts.tv_sec, ts.tv_nsec);
      return 0;
    }
    

3. 格式化时间

localtime() / gmtime()

  • 功能:将 time_t 转换为本地时间或 UTC 时间的结构体 struct tm
  • 示例

    #include <time.h>
    #include <stdio.h>
    
    int main() {
      time_t t = time(NULL);
      struct tm *local = localtime(&t);
      printf("Local time: %d-%02d-%02d %02d:%02d:%02d\n",
             local->tm_year + 1900, local->tm_mon + 1, local->tm_mday,
             local->tm_hour, local->tm_min, local->tm_sec);
      return 0;
    }
    

strftime()

  • 功能:将 struct tm 格式化为字符串。
  • 示例c char buffer[80]; strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local); printf("Formatted: %s\n", buffer);

4. 高精度计时(性能分析)

clock()

  • 头文件: <time.h>
  • 返回值: 程序消耗的 CPU 时钟周期(需除以 CLOCKS_PER_SEC 转换为秒)。
  • 示例c clock_t start = clock(); // ... 执行代码 ... double cpu_time = (double)(clock() - start) / CLOCKS_PER_SEC;

5. C++ 中的替代方案

  • <chrono>(C++11 及以上):

    #include <chrono>
    #include <iostream>
    
    int main() {
      auto now = std::chrono::system_clock::now();
      auto timestamp = std::chrono::system_clock::to_time_t(now);
      std::cout << "Timestamp: " << timestamp << std::endl;
      return 0;
    }
    

如何选择?

  • 简单时间戳time()
  • 高精度clock_gettime()
  • 格式化输出localtime() + strftime()
  • 跨平台 C++<chrono>

如果需要进一步优化或特定场景的用法,可以深入探讨某个函数的具体实现细节!