Reputation: 757
How can I measure time required to create and launch thread? (Linux, pthreads or boost::thread).
Thanks for advices!
Upvotes: 0
Views: 1731
Reputation: 70206
You should probably specify what exactly you want to measure, since there are at least 2 possible interpretations (the time the original thread is "busy" inside pthread_create
versus the time from calling pthread_create
until the other thread actually executes its first instruction).
In either case, you can query monotonic real time using clock_gettime
with CLOCK_MONOTONIC
before and after the call to pthread_create
or before the call and as the first thing inside the thread funciton. Then, subtract the second value from the first.
To know what time is spent inside phtread_create
, CLOCK_THREAD_CPUTIME_ID
is an alternative, as this only counts the actual time your thread used.
Alltogether, it's a bit pointless to measure this kind of thing, however. It tells you little to nothing at all about how it will behave under real conditions on your system or another system, with unknown processes and unknown scheduling strategies and priorities.
On another machine, or on another day, your thread might just be scheduled 100 or 200 milliseconds later. If you depend on the fact that this won't happen, you're dead.
EDIT:
In respect of the info added in above comment, if you need to "perform actions on non-regular basis" on a scale that is well within "normal scheduling quantums", you can just create a single thread and nanosleep
for 15 or 30 milliseconds. Of course, sleep is not terribly accurate or reliable, so you might instead want to e.g. block on a timerfd
(if portability is not topmost priority, otherwise use a signal-delivering timer).
It's no big problem to schedule irregular intervals with a single timer/wait either, you only need to keep track of when the next event is due. This is how modern operating systems do it too (read up on "timer coalescing").
Upvotes: 2