Linux系统时间有两种。
(1)日历时间。该值是自协调世界时(UTC)1970年1月1日00:00:00这个特定时间以来所经过的秒数累计值。基本数据类型用time_t
保存。最后通过转换才能得到我们平时所看到的24小时制或者12小时间制的时间。
(2)进程时间。也被称为CPU时间,用以度量进程使用的中央处理器资源。进程时间以时钟滴答计算。
日历时间
time()获取时间戳
time函数用来获取日历时间的时间戳,该时间戳是从1970年1月1日0点(00:00:00 UTC, January 1, 1970)到现在经历的秒数。
函数定义如下:
#include <time.h>
time_t time(time_t *calptr)
time
返回当前时间的时间戳,也就是从世界时到现在的秒数;time_t
实际系统自定义的时间戳类型,函数正常返回当前时间戳,出错返回(time_t)-1
;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(NU