在 Linux 系统中,获取时间的函数有多种,适用于不同场景和精度需求。以下是常用的时间获取函数分类及示例:
time()<time.h>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() 替代。
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;
}
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);clock()<time.h>CLOCKS_PER_SEC 转换为秒)。c
clock_t start = clock();
// ... 执行代码 ...
double cpu_time = (double)(clock() - start) / CLOCKS_PER_SEC;<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()<chrono>如果需要进一步优化或特定场景的用法,可以深入探讨某个函数的具体实现细节!