| #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系统编程手册
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。








