MATLAB's tic-toc & C's clock discrepancy

后端 未结 1 1764
粉色の甜心
粉色の甜心 2021-01-18 00:31

I have written some C code which I call form MATLAB after I compile it using MEX. Inside the C code, I measure the time of a part of the computation using the follo

相关标签:
1条回答
  • 2021-01-18 01:15

    You're comparing apples to oranges.

    Look at Matlab's documentation:

    tic - http://www.mathworks.com/help/matlab/ref/tic.html
    toc - http://www.mathworks.com/help/matlab/ref/toc.html

    tic and toc let you measure real elapsed time.

    Now look at the clock function http://linux.die.net/man/3/clock.

    In particular,

    The clock() function returns an approximation of processor time used by the program.

    The value returned is the CPU time used so far as a clock_t; to get the number of seconds used, divide by CLOCKS_PER_SEC. If the processor time used is not available or its value cannot be represented, the function returns the value (clock_t) -1.

    So what can account for your difference:

    • CPU time (measured by clock()) and real elapsed time (measured by tic and toc) are NOT the same. So you would expect that cpu time to be less than elapsed time? Well, maybe. What if within 0.0011s you're driving 10 cores at 100%? That would mean that clock() measurement is 10x that measured with tic and toc. Possible, unlikely.
    • clock(.) is grossly inaccurate, and consistent with the documentation, it is an approximate cpu time measurement! I suspect that it is pegged to the scheduler quantum size, but I didn't dig through the Linux kernel code to check. I also didn't check on other OSes, but this dude's blog is consistent with that theory.

    So what to do... for starters, compare apples to apples! Next, make sure you take into account timer resolution.

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