How to print time difference in accuracy of milliseconds and nanoseconds from C in Linux?

前端 未结 2 1595
深忆病人
深忆病人 2020-11-30 04:43

I have this program which prints the time difference between 2 different instances, but it prints in accuracy of seconds. I want to print it in milliseconds and another in n

2条回答
  •  悲哀的现实
    2020-11-30 05:34

    Read first the time(7) man page.

    Then, you can use clock_gettime(2) syscall (you may need to link -lrt to get it).

    So you could try

        struct timespec tstart={0,0}, tend={0,0};
        clock_gettime(CLOCK_MONOTONIC, &tstart);
        some_long_computation();
        clock_gettime(CLOCK_MONOTONIC, &tend);
        printf("some_long_computation took about %.5f seconds\n",
               ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - 
               ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));
    

    Don't expect the hardware timers to have a nanosecond accuracy, even if they give a nanosecond resolution. And don't try to measure time durations less than several milliseconds: the hardware is not faithful enough. You may also want to use clock_getres to query the resolution of some clock.

提交回复
热议问题