1、单调时间
linux下编写应用程序时,涉及到时间获取有多个函数可以选择,这些常用获取时间函数之间的差异:
《1》、 time
该函数返回自1970来的秒数,精度过低;
《2》、gettimeofday
该函数返回自1970年以来的秒数和微秒数,精度足够,符合一般场景的使用期望。但是如果系统时间因为ntp等原因发生时间调变,那么用这个函数来计算相对时间就很可能会出问题,此种情况下就不要使用该函数。
注意:
该函数timeval结构体内的tv_sec是time_t类型的,即是long类型。在32位系统下为4字节,能够表示的最大整数是2147483647,这个数代表的时间是2038-01-19 03:14:07,超过这个时间点后变为-2147483647,这个就是linux 2038年问题。在64位系统下不用担心溢出问题,因为此时long类型为8字节(能表示几千亿年)。
《3》、 clock_gettime
该函数返回自系统启动后的秒数和纳秒数,精度很高。该函数提供八种类型clock,见下图。其中CLOCK_MONOTONIC提供了单调递增的时间戳【单调时间】。
不过该函数没有考虑ntp的情况,所以并不是绝对意义上的单调递增。
《4》、syscall(SYS_clock_gettime, CLOCK_MONOTONIC_RAW, struct timespec*tp)
 该函数提供了真正意义上的单调递增时间。
struct timespec {
time_t tv_sec; // seconds
long tv_nsec; // and nanoseconds
};
struct timeval {
time_t tv_sec; // seconds
long tv_usec; // microseconds
};
struct timezone{
int tz_minuteswest; //miniutes west of Greenwich
int tz_dsttime; //type of DST correction
};
实例:
#include <stdio.h>
#include<unistd.h>
#include<time.h>
#include<sys/time.h>
#include<stdint.h>
#include<sys/syscall.h>
int main()
{
struct timeval tv;
gettimeofday(&tv, NULL);
int64_t ms_time = (int64_t)tv.tv_sec*1000 + tv.tv_usec/1000;
//(int64_t)类型转换对于32位的系统是必须的,否则乘上1000会溢出
printf("gettimeofday: sec = %ld, usec = %ld\n", tv.tv_sec, tv.tv_usec);
struct timespec tp;
syscall(SYS_clock_gettime, CLOCK_MONOTONIC_RAW, &tp);
printf("SYS_clock_gettime: sec = %ld, nsec = %ld\n", tp.tv_sec, tp.tv_nsec);
return 0;
}
2、墙上时钟时间、用户CPU时间,系统CPU时间
时钟时间: 从进程开始运行到结束,时钟走过的时间,这其中包含了进程阻塞和等待状态的时间。其值与系统中同时运行的进程数有关。
用户CPU时间: 进程获得CPU资源之后,在用户态执行的时间(执行用户指令所用的时间量);
系统CPU时间: 用户进程获得CPU资源之后,在内核态的执行时间。
CPU时间 = 用户CPU时间 + 系统CPU时间;
获取进程的时钟时间、用户时间和系统时间可以使用下两中方法:
《1》time命令
time exe_file_name
《2》使用times函数获得
#include <sys/times.h>
clock_t times(struct tms *buf)
//返回值:若成功,返回流逝的墙上时钟时间(以时钟滴答数为单位),若出错,返回-1
struct tms
{
clock_t tms_utime; /*user CPU time*/
clock_t tms_stime; /*system CPU time*/
clock_t tms_cutime; /*user CPU time, terminated children 子进行用户 CPU 时间*/
clock_t tms_sctime; /*system CPU time, terminated children 子进行系统 CPU 时间*/
};
3、参考:
《1》、《unix环境高级编程》第三版-- 1.10,8.17
《2》、https://www.cnblogs.com/vinozly/p/5078755.html
《3》、https://blog.youkuaiyun.com/sollor525/article/details/74202550