获取线程在CPU的执行时间

13 篇文章 0 订阅
  1. 总览

    • 说明

      • 通过linux下的接口实现.
    • 参考

  2. 案例

    • 代码

      #include<pthread.h>
      #include<stdio.h>
      #include<time.h>
      #include<unistd.h>
      int main() {
             clockid_t st;
             struct timespec ts,te;
             if(pthread_getcpuclockid(pthread_self();,&st)){return 0;}
             if(clock_gettime(st,&ts)){return 0;}
             printf("%09ld.%09ld\n",ts.tv_sec,ts.tv_nsec);
      
             for(int i = 0 ; i < 1000000000 ; i++){}
             sleep(1);
             
             if(clock_gettime(st,&te)){return 0;}
             printf("%09ld.%09ld\n",te.tv_sec,te.tv_nsec);
      }
      
    • 编译

      g++ -g -pthread test.cpp
      
    • 执行结果

      ch@chvm:~/ch/exam/cpu_clock$ time ./a.out
      000000000.000596603
      000000001.519019122
      
      real    0m2.520s
      user    0m1.516s
      sys     0m0.004s
      
      
    • C++版本

      class CpuTimer {
      public:
         CpuTimer(){
             pthread_getcpuclockid(pthread_self(),&id_);
             clock_gettime(id_,&ts_);
             struct sched_param param{.sched_priority=10};
             if(pthread_setschedparam(pthread_self(),SCHED_FIFO,&param)){
                 LOGE("sched-error");
             }
         }
         ~CpuTimer(){
             clock_gettime(id_,&te_);
             LOGE("cputime %lld",(te_.tv_sec-ts_.tv_sec)*1000000000ll+te_.tv_nsec-ts_.tv_nsec);
             struct sched_param param{.sched_priority=0};
             if(pthread_setschedparam(pthread_self(),SCHED_OTHER,&param)){
                 LOGE("sched-error");
             }
         }
      private:
         clockid_t id_;
         struct timespec ts_,te_;
      };
      
      
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值