Reputation: 2038
How does the clock
function work behind the scene in a multithreading program?
AFAIK, the clock function provided by the C standard library could be used to measure the CPU time consumed by the running program, but how does this process work under the hood? Is the underlying hardware timer part of the CPU chip? If it's not, how does the clock know when the CPU is scheduled to run the current program? Since the clock
function only records the time consumption of each individual CPU that executes the current program. Meaning in a multi-threaded program, the returned value would be lower than the wall-clock time.
*Although I raised another question in What's the relationship between the real CPU frequency and the clock_t in C?, but actually, those are two different topics, so, I don't want to mix them up in one post.
Upvotes: 4
Views: 437
Reputation: 51894
Since the clock function only records the time consumption of each individual CPU that executes the current program. Meaning in a multi-threaded program, the returned value would be lower than the wall-clock time.
I can't find a definitive statement in a C Standard but, according to cppreference (which is generally very reliable), your assumption is wrong and the clock()
function returns the total (for all CPUs) processor time used by the program (bold emphasis mine):
… For example, if the CPU is shared by other processes, clock time may advance slower than wall clock. On the other hand, if the current process is multithreaded and more than one execution core is available, clock time may advance faster than wall clock.
Upvotes: 2