tags:

views:

108

answers:

3

Do calling an API function considered an expensive operation? (when comparing it to a function call which is part of my application)
I understand that some API functions cause a leap to kernel mode but is it true for all of them?

More specific: how expensive will it be to call GetThreadId function?

+4  A: 

GetThreadId of an arbitrary thread requires a kernel switch, so it more expensive than GetCurrentThreadId which retrieves cached data from user mode.

The cost of an API is highly dependent on the nature of the API itself. An API that retrieves a cached value from user mode is very cheap, an API that transitions to kernel mode is much more expensive, on the order of microseconds. API's that read or write to disk can cost dozens of milliseconds. API's that work on the network can take seconds or minutes.

Michael
+2  A: 

Moderately cheap. There's a user/kernel mode transition, but in the kernel, it's just a simple memory read. Dereference the handle, grab the ID from the structure.

More specific: what viable alternatives do you see?

EDIT: unless it's the current thread ID that you're after. GetCurrentThreadId() is completely user-mode, therefore very, very cheap.

Seva Alekseyev
+2  A: 

This is not so for all of them. For most API calls, it's just a call to something inside a DLL and do not require a mode transition. In this case it will be a few to tens of nanoseconds per call.

Pavel Radzivilovsky
(+1) for the clarification :P
Hassan Syed