Calculating Function time in nanoseconds in C code

前端 未结 4 1186
栀梦
栀梦 2020-12-19 07:29

I need to know how can I calculate the time of a function in C code in nanoseconds. I tried to repeat the function until consume some microseconds. Are there any other funct

4条回答
  •  轮回少年
    2020-12-19 07:56

    Call the function enough times that you get total time in the seconds, and use any method to measure (even plain C clock()). Measuring in micro/nanoseconds is inherently too imprecise.

    For benchmarking, you want QueryPerformanceCounter. It is the best stopwatch available on Windows. See: How to use QueryPerformanceCounter? However using this to measure (for example) a single function call will still be inherently very imprecise; I think you need to time on the order of a second total to get good signal-to-noise ratio for your measurements. Take multiple measurements of whatever duration you want and compare their value to their standard deviation to make sure you are measuring sufficiently accurately.

    Multimedia Timers are probably the best clock (note the difference between clock and stopwatch: one measures absolute time, the other time intervals only) available on Windows. You should be able to get near-millisecond resolution and precision with timeGetTime().

提交回复
热议问题