linux系统时间 time.h 之clock( )函数使用

/*
  2 clock返回自程序运行以来,所耗费的处理时间。它的单位并非秒,除以CLOCKS_PER_SEC才是秒
  3 eg:clock与CLOCKS_PER_SEC搭配使用
  4 clock_t start,end;start=clock();(执行要计算的执行时间的程序代码);end=clock();
  5 double sub;sub=(double(end-start))/CLOCK_PER_SEC;得到程序运行的时间,单位秒
  6 */
  7 /*
  8 CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时>    间被用户该成其他,则对应的时间相应改变
  9 CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响
 10 CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间
 11 CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间
 12 ##int clock_gettime(clockid_t clk_id,struct timespec * tp);
 13 ##int clock_settime(clockid_t clock_id,const struct timespec * tp);
 14 struct timespec
 15 {
 16        time_t tv_sec; 秒
 17        long tv_nsec; 纳秒
};
 19 */
 20 #include <stdio.h>
 21 #include <time.h>
 22 #include <stdlib.h>
 23 #include <threads.h> // pthread.h in POSIX
 24  
 25 // the function f() does some time-consuming work
 26 int f(void* thr_data) // return void* in POSIX
 27 {
 28     volatile double d = 0;
 29     for (int n=0; n<10000; ++n)
 30        for (int m=0; m<10000; ++m)
 31            d += d*n*m;
 32     return 0;
 33 }
 34  
 35 int main(void)
 36 {
 37     struct timespec ts1, tw1; // both C11 and POSIX
 38     clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts1); // POSIX
 39     clock_gettime(CLOCK_MONOTONIC, &tw1); // POSIX; use timespec_get in C11
 40     clock_t t1 = clock();
 41  
 42     thrd_t thr1, thr2;  // C11; use pthread_t in POSIX
 43     thrd_create(&thr1, f, NULL); // C11; use pthread_create in POSIX
 44     thrd_create(&thr2, f, NULL);
 45     thrd_join(thr1, NULL); // C11; use pthread_join in POSIX
 46     thrd_join(thr2, NULL);
 47  
 48     struct timespec ts2, tw2;
 49     clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts2);
 50     clock_gettime(CLOCK_MONOTONIC, &tw2);
 51     clock_t t2 = clock();
 53     double dur = 1000.0*(t2-t1)/CLOCKS_PER_SEC;
 54     double posix_dur = 1000.0*ts2.tv_sec + 1e-6*ts2.tv_nsec
 55                        - (1000.0*ts1.tv_sec + 1e-6*ts1.tv_nsec);
 56     double posix_wall = 1000.0*tw2.tv_sec + 1e-6*tw2.tv_nsec
 57                        - (1000.0*tw1.tv_sec + 1e-6*tw1.tv_nsec);
 58 
 59     printf("CPU time used (per clock(): %.2f ms\n", dur);
 60     printf("CPU time used (per clock_gettime()): %.2f ms\n", posix_dur);
 61     printf("Wall time passed: %.2f ms\n", posix_wall);
 62 }
 63 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值