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

后端 未结 11 1832
花落未央
花落未央 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 <time.h>
    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

    0 讨论(0)
  • 2020-12-31 05:30

    You won't find a library call which lets you get past the clock resolution of your platform. Either use a profiler (man gprof) as another poster suggested, or - quick & dirty - put a loop around the offending section of code to execute it many times, and use clock().

    0 讨论(0)
  • 2020-12-31 05:33

    Try "bench.h"; it lets you put a START_TIMER; and STOP_TIMER("name"); into your code, allowing you to arbitrarily benchmark any section of code (note: only recommended for short sections, not things taking dozens of milliseconds or more). Its accurate to the clock cycle, though in some rare cases it can change how the code in between is compiled, in which case you're better off with a profiler (though profilers are generally more effort to use for specific sections of code).

    It only works on x86.

    0 讨论(0)
  • 2020-12-31 05:39

    You might want to google for an instrumentation tool.

    0 讨论(0)
  • 2020-12-31 05:40

    It depends on the conditions.. Profilers are nice for general global views however if you really need an accurate view my recommendation is KISS. Simply run the code in a loop such that it takes a minute or so to complete. Then compute a simple average based on the total run time and iterations executed.

    This approach allows you to:

    1. Obtain accurate results with low resolution timers.

    2. Not run into issues where instrumentation interferes with high speed caches (l2,l1,branch..etc) close to the processor. However running the same code in a tight loop can also provide optimistic results that may not reflect real world conditions.

    0 讨论(0)
  • 2020-12-31 05:44

    You want a profiler application.

    Search keywords at SO and search engines: linux profiling

    0 讨论(0)
提交回复
热议问题