0

I'm currently learning C to optimize the implementation of various algorithms (that I currently have implemented in Python).

To help me compare C and Python implementations, I'm looking to measure the function's execution time.

Using Python, the iPython REPL offers the fantastic %timeit functionality, which effectively repeats the function many times and displays the average execution time and an indication of variation over the many times it was performed? This works for execution times varying from nanoseconds to many seconds.

In C, I've read about a time command that can be added to code to report the single-run execution time. However, this has 2 limitations:

1) only millisecond resolution

2) it's only a 'single-run' measurement.

Therefore, my question is: are there any better / alternative approaches or packages for C that will enable quick yet accurate (i.e. even working for fast ns-execution time functions) display of execution times?

Rashed Hasan
  • 3,721
  • 11
  • 40
  • 82
SLhark
  • 177
  • 10
  • 1
    There's nothing built-in. `%timeit` runs the code many times to get the average time, you just have to do the same thing in your C program. – Barmar Oct 26 '19 at 08:25
  • Ok, this makes sense. But is there a way to get ns resolution? The `C` time function seems limited to ms which is too slow for precise profiling – SLhark Oct 26 '19 at 08:38
  • are you telling us you are unable to get your function to run enough times to get in the millisecond range? what are you trying to time, `return` statement? – lenik Oct 26 '19 at 08:40
  • Oh ok, so run it 10000x times then get the overall time. This would work, but doesn't give any indication of variation between executions. – SLhark Oct 26 '19 at 08:45
  • 1
    Depending on your system, you may be able to call `gettimeofday` to get time with microsecond resolution, or `clock_gettime` to get nanosecond resolution. Or you can call `clock()` to get CPU time with subsecond resolution determined by `CLOCKS_PER_SEC`. (And with `clock_gettime` you can choose between wall, elapsed, or CPU time.) – Steve Summit Oct 26 '19 at 12:09
  • 1
    See also [this other question](https://stackoverflow.com/questions/57439219/comparing-execution-time-of-two-functions) for some guidance. – Steve Summit Oct 26 '19 at 12:16

0 Answers0