Linux系统时间有两种。
(1)日历时间。该值是自协调世界时(UTC)1970年1月1日00:00:00这个特定时间以来所经过的秒数累计值。基本数据类型用time_t保存。最后通过转换才能得到我们平时所看到的24小时制或者12小时间制的时间。
(2)进程时间。也被称为CPU时间,用以度量进程使用的中央处理器资源。进程时间以时钟滴答计算。
本文将给大家详细介绍关于Linux时间的获取和使用,下面话不多说了,来一起看看详细的介绍吧
获取时间戳
time()
| #include <time.h> time_t time(time_t *calptr) |
调用示例:
| #include <time.h> #include <iostream> #include <stdlib.h> using namespace std; int main() { time_t curTime; curTime = time(NULL); cout << curTime << endl; return 0; } |
结果:
返回一串数值,如1533287924
gettimeofday()和clock_gettime()
time函数只能得到秒精度的时间,为了获得更高精度的时间戳,需要其他函数。gettimeofday函数可以获得微秒精度的时间戳,用结构体timeval来保存;clock_gettime函数可以获得纳秒精度的时间戳,用结构体timespec来保存。
| #include <sys/time.h> int gettimeofday(struct timeval *tp, void *tzp); 因为历史原因tzp的唯一合法值是NULL,因此调用时写入NULL即可。 int clock_gettime(clockid_t clock_id, strcut timespec *tsp); clock_id有多个选择,当选择为CLOCK_REALTIME时与time的功能相似,但是时间精度更高。 |
两个函数使用的结构体定义如下:
| struct timeval { long tv_sec; /*秒*/ long tv_usec; /*微秒*/ }; struct timespec { time_t tv_sec; //秒 long tv_nsec; //纳秒 }; |
调用示例:
| #include <time.h> #include <sys/time.h> #include <iostream> #include <stdlib.h> using namespace std; int main() { time_t dwCurTime1; dwCurTime1 = time(NULL); struct timeval stCurTime2; gettimeofday(&stCurTime2, NULL); struct timespec stCurTime3; clock_gettime(CLOCK_REALTIME, &stCurTime3); cout << "Time1: " << dwCurTime1 << "s" << endl; cout << "Time2: " << stCurTime2.tv_sec << "s, " << stCurTime2.tv_usec << "us" << endl; cout << "Time3: " << stCurTime3.tv_sec << "s, " << stCurTime3.tv_nsec << "ns" << endl; return 0; } |
结果:
编译时要在编译命令最后加上-lrt链接Real Time动态库,如
g++ -o time2 test_time_linux_2.cpp -lrt








