Nick
Nick

Reputation: 2575

Determine on which physical processor my code is currently running

Is there a Windows API or any way to determine on which physical processor/core my current thread runs? I don't need that information. I'm just curious.

I'm not interested in the processors the thread is allowed to run on. I would like to know on exactly which one it currently runs. I know that the threads switch pretty fast from one to another...

Upvotes: 3

Views: 4323

Answers (3)

Eric Petroelje
Eric Petroelje

Reputation: 60498

Threads will often switch from processor to processor, so it's kind of meaningless, but you can use GetCurrentProcessorNumber.

As others have said, you can use GetProcessAffinityMask or GetThreadIdealProcessor, but those will only work if you've already set an affinity mask or ideal processor for the thread.

Upvotes: 4

Simon Steele
Simon Steele

Reputation: 11608

For controlling which processor your process or thread runs on using the Windows API you can use SetThreadAffinityMask or SetProcessAffinityMask.

These work by setting bits in a bit mask, where each bit represents a processor your thread or process can be scheduled for:

BOOL WINAPI SetProcessAffinityMask(
  __in  HANDLE hProcess,
  __in  DWORD_PTR dwProcessAffinityMask
);

Call GetProcessAffinityMask to discover which processors are available for use in these calls.

Upvotes: 2

Rowland Shaw
Rowland Shaw

Reputation: 38130

You can query the processor affinity with GetProcessAffinityMask. If you haven't set processor affinity, I'm unsure how useful the result will be though, as the thread can flit between processors.

Upvotes: 3

Related Questions