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

后端 未结 11 1833
花落未央
花落未央 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:44

    Don't know which enviroment/OS you are working on, but your timing may be inaccurate if another thread, task, or process preempts your timed code in the middle. I suggest exploring mechanisms such as mutexes or semaphores to prevent other threads from preemting your process.

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

    Have a look at gettimeofday, clock_*, or get/setitimer.

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

    You referred to clock() and time() - were you looking for gettimeofday()? That will fill in a struct timeval, which contains seconds and microseconds.

    Of course the actual resolution is up to the hardware.

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

    If you are developing on x86 or x64 why not use the Time Stamp Counter: RDTSC.

    It will be more reliable then Ansi C functions like time() or clock() as RDTSC is an atomic function. Using C functions for this purpose can introduce problems as you have no guarantee that the thread they are executing in will not be switched out and as a result the value they return will not be an accurate description of the actual execution time you are trying to measure.

    With RDTSC you can better measure this. You will need to convert the tick count back into a human readable time H:M:S format which will depend on the processors clock frequency but google around and I am sure you will find examples.

    However even with RDTSC you will be including the time your code was switched out of execution, while a better solution than using time()/clock() if you need an exact measurement you will have to turn to a profiler that will instrument your code and take into account when your code is not actually executing due to context switches or whatever.

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

    gettimeofday() provides you with a resolution of microseconds, whereas clock_gettime() provides you with a resolution of nanoseconds.

    int clock_gettime(clockid_t clk_id, struct timespec *tp);
    

    The clk_id identifies the clock to be used. Use CLOCK_REALTIME if you want a system-wide clock visible to all processes. Use CLOCK_PROCESS_CPUTIME_ID for per-process timer and CLOCK_THREAD_CPUTIME_ID for a thread-specific timer.

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