How can I find the execution time of a section of my program in C?

后端 未结 11 1938
花落未央
花落未央 2020-12-31 05:23

I\'m trying to find a way to get the execution time of a section of code in C. I\'ve already tried both time() and clock() from time.h, but it seems that time() returns seco

11条回答
  •  天涯浪人
    2020-12-31 05:29

    For what it's worth, here's one that's just a few macros:

    #include 
    clock_t startm, stopm;
    #define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
    #define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
    #define PRINTTIME printf( "%6.3f seconds used by the processor.", ((double)stopm-startm)/CLOCKS_PER_SEC);
    

    Then just use it with:

    main() {
      START;
      // Do stuff you want to time
      STOP;
      PRINTTIME;
    }
    

    From http://ctips.pbwiki.com/Timer

提交回复
热议问题