I'm going to use id of current running thread in a very performance critical place in my code, so I should choose whether to cache that id somewhere or to call a method (gettid
for unix-like systems and GetCurrentThreadId
for windows) for getting it every time. So which is better? Is getting thread id a system call?
The thread ID is used by the operating system to identify processes and threads. The thread id is unique globally but the users can capture the thread handle of the process thread through this id.
In some threads implementations, the thread ID is a 4-byte integer that starts at 1 and increases by 1 every time a thread is created. This integer can be used in a non-portable fashion by an application.
At least in Windows, GetCurrentThreadId()
is quite cheap, and does not involve a system call. Basically it works out to:
int GetCurrentThreadId() {
_asm {
mov eax, fs:[18h]
mov eax, [eax+24h]
}
}
There could be a little benefit to caching the value in your own variable, but not a lot. The main benefit would probably be if you stored your variable along with other frequently used variables, which could improve locality (and therefore cache usage).
So, unless you're working on such a tight loop that the possibility of eliminating a memory fetch (or possibly two) is significant, you're unlikely to gain much by caching the value it returns.
No, it is not an expensive call. It is a system call or similar, but far from an expensive one. Obviously, if you can cache the value in a simple variable then that would make it faster by a factor of 10.
But like all performance related queries, it's really down to your benchmarking. You can pretty easily set things up to use a single thread, call the function to get the thread ID, and do what you want to do. Measure how long it takes to run some test with that. Then replace the call for the thread ID with a constant value in the same range, and see how that works out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With