views:

50

answers:

2

Hello,

I need to implement a method that can measure Time and CPU cycles of context switch between threads in Windows.

Here is my code

#include <stdio.h>
#include <windows.h>
#include <time.h>

LARGE_INTEGER initialTimeStamp, finalTimeStamp, freq;

DWORD ThreadProc(LPVOID lpdwThreadParam)
{
 SwitchToThread();
 return 0;
}

int main()
{
  int result;
  HANDLE hThread;
  QueryPerformanceFrequency(&freq);
  hThread = CreateThread(NULL,0, (LPTHREAD_START_ROUTINE)ThreadProc,NULL, 0, 0);

  QueryPerformanceCounter(&initialTimeStamp);
  SwitchToThread();
  QueryPerformanceCounter(&finalTimeStamp);

  result = (1000000 * ((finalTimeStamp.QuadPart - initialTimeStamp.QuadPart) / 2 ) / freq.QuadPart);
  printf("Windows Thread - context switch time is %u ns\n", result);  

  WaitForSingleObject(hThread, INFINITE);
  return 0;
}

Note: The division by two, is because I have two context switch between initialTimeStamp and finalTimeStamp.

I don't know if this is a best or correct way to do it... I get different time on each execution, which is not what I was expecting. I'm not sure how to get a number of CPU cycles.

Any help will be appreciated.

A: 

You are getting different times because computer performance is very variable.

Alexander Rafferty
+1  A: 

You will actually have to have a thread that is burning CPU cycles to get SwitchToThread() to actually make a context switch. More than one if your CPU has multiple cores. Even then, the result you'll get is largely meaningless. The amount of overhead is highly variable depending on the process that owns the thread that gets the quantum and the state of the TLB cache. Reloading the TLB registers and getting cache misses adds lots of time. The usual number thrown about is between 2,000 and 10,000 cycles.

Hans Passant
By replacing SwitchToThread() to Sleep(0) will solve this or not? There must be a way get approximate time.