Linux系统中时间的获取和使用

2019-01-16 20:50:38于海丽

#include <time.h> clock_t clock(void) //if error, return -1

clock函数返回值得计量单位是CLOCKS_PER_SEC,将返回值除以这个计量单位就得到了进程时间的秒数

times函数

times函数也是一个进程时间函数,有更加具体的进程时间表示,函数定义如下:

#include <sys/times.h> clock_t times(struct tms* buf); struct tms{ clock_t tms_utime; clock_t tms_stime; clock_t tms_cutime; clock_t tms_cstime; };

times函数虽然返回类型还是clock_t,但是与clock函数返回值的计量单位不同。times函数的返回值得计量单位要通过sysconf(SC_CLK_TCK)来获得。

Linux系统编程手册上一个完整的使用案例如下:

#include <time.h> #include <sys/times.h> #include <unistd.h> #include <stdio.h> static void displayProcessTime(const char* msg) { struct tms t; clock_t clockTime; static long clockTick = 0; if (msg != NULL) { printf("%sn", msg); } if (clockTick == 0) { clockTick = sysconf(_SC_CLK_TCK); if (clockTick < 0) return; } clockTime = clock(); printf("clock return %ld CLOCKS_PER_SEC (%.2f seconds)n", (long)clockTime, (double)clockTime/CLOCKS_PER_SEC); times(&t); printf("times return user CPU = %.2f; system CPU = %.2fn", (double)t.tms_utime / clockTick, (double)t.tms_stime / clockTick); } int main() { printf("CLOCKS_PER_SEC = %ld, sysconf(_SC_CLK_TCK) = %ldn", (long)CLOCKS_PER_SEC, sysconf(_SC_CLK_TCK)); displayProcessTime("start:"); for (int i = 0; i < 1000000000; ++i) { getpid(); } printf("n"); displayProcessTime("end:"); return 0; }

参考

[1] http://www.runoob.com/w3cnote/cpp-time_t.html

[2] Unix高级环境编程(第三版)

[3] Unix系统编程手册

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。

您可能感兴趣的文章:

Windows和 Linux下生成以当前时间命名文件的方法Linux下date命令,格式化输出,时间设置方法解析Linux下的时间函数:设置以及获取时间的方法Linux 按时间批量删除文件命令(删除N天前文件)linux获取进程执行时间方法示例程序中获取linux系统启动时间方法基于linux下获取时间函数的详解linux获取系统启动时间示例详解Linux 判断文件修改时间和系统时间差Linux/Unix关于时间和时间戳的命令行