-
总览
-
案例
-
代码
#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,¶m)){ 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,¶m)){ LOGE("sched-error"); } } private: clockid_t id_; struct timespec ts_,te_; };
-
获取线程在CPU的执行时间
最新推荐文章于 2023-12-23 23:52:17 发布