在Linux系统中,可以通过多种方式计算时间,包括C/C++标准库函数、系统调用和命令行工具。以下是详细的分类说明:
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 (纳秒)
strftime()
c
char buf[64];
time_t now = time(NULL);
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", localtime(&now));
clock()
c
clock_t start = clock();
// ... 执行代码 ...
double cpu_time = (double)(clock() - start) / CLOCKS_PER_SEC;
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);
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...
#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;
单调时钟(Monotonic Clock)
使用CLOCK_MONOTONIC
避免系统时间跳变的影响(适合计时场景):
clock_gettime(CLOCK_MONOTONIC, &ts);
时区处理
使用localtime_r
(线程安全)或setenv("TZ", "UTC", 1)
修改时区。
性能分析工具
复杂场景可结合perf
、strace
或gprof
进行更深入的分析。
根据具体需求选择合适的函数:
- 简单计时 → time()
或 std::chrono
- 高精度 → clock_gettime()
- 跨平台 → C++11的<chrono>
- 命令行 → date
/time
命令