Measuring amount of CPU time taken by a piece of code, in C on Unix/Linux

后端 未结 6 1030
旧时难觅i
旧时难觅i 2021-01-05 13:18

Can clock() be used as a dependable API to measure time taken by CPU to execute a snippet of code? When verified usng times() / clock(), both do not seem to measure the CPU

6条回答
  •  遥遥无期
    2021-01-05 14:07

    Some info here on HP's page about high resolution timers. Also, same trick _Asm_mov_from_ar (_AREG_ITC); used in http://www.fftw.org/cycle.h too.

    Have to confirm if this can really be the solution.

    Sample prog, as tested on HP-UX 11.31:

    bbb@m_001/tmp/prof > ./perf_ticks 1024
    ticks-memset {func [1401.000000] inline [30.000000]} noop [9.000000]
    bbb@m_001/tmp/prof > cat perf_ticks.c
    #include 
    #include 
    #include 
    #include 
    #include 
    #include "cycle.h" /* one from http://www.fftw.org/cycle.h */
    void test_ticks(char* sbuf, int* len){
        memset((char*)sbuf,0,*len);
    }
    int main(int argc,char* argv[]){
            int len=atoi(argv[1]);
            char *sbuf=(char*)malloc(len);
            ticks t1,t2,t3,t4,t5,t6;
            t1 =getticks(); test_ticks(sbuf,&len); t2 =getticks();
            t3 =getticks(); memset((char*)sbuf,0,len); t4 =getticks();
            t5=getticks();;t6=getticks();
            printf("ticks-memset {func [%llf] inline [%llf]} noop [%llf]\n",
                              elapsed(t2,t1),elapsed(t4,t3),elapsed(t6,t5));
            free(sbuf); return 0;
    }
    bbb@m_001/tmp/prof >
    

提交回复
热议问题