Skip to content

Instantly share code, notes, and snippets.

@gylns
Created August 19, 2016 01:17
Show Gist options
  • Save gylns/656415db2ed9c1da705fd2229b70b05e to your computer and use it in GitHub Desktop.
Save gylns/656415db2ed9c1da705fd2229b70b05e to your computer and use it in GitHub Desktop.
// from http://stackoverflow.com/questions/800383/what-is-the-difference-between-mutex-and-critical-section
// a performance testing between mutex and CRITICAL_SECTION on windows
HANDLE mutex = CreateMutex(NULL, FALSE, NULL);
CRITICAL_SECTION critSec;
InitializeCriticalSection(&critSec);
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
LARGE_INTEGER start, end;
// Force code into memory, so we don't see any effects of paging.
EnterCriticalSection(&critSec);
LeaveCriticalSection(&critSec);
QueryPerformanceCounter(&start);
for (int i = 0; i < 1000000; i++)
{
EnterCriticalSection(&critSec);
LeaveCriticalSection(&critSec);
}
QueryPerformanceCounter(&end);
int totalTimeCS = (int)((end.QuadPart - start.QuadPart) * 1000 / freq.QuadPart);
// Force code into memory, so we don't see any effects of paging.
WaitForSingleObject(mutex, INFINITE);
ReleaseMutex(mutex);
QueryPerformanceCounter(&start);
for (int i = 0; i < 1000000; i++)
{
WaitForSingleObject(mutex, INFINITE);
ReleaseMutex(mutex);
}
QueryPerformanceCounter(&end);
int totalTime = (int)((end.QuadPart - start.QuadPart) * 1000 / freq.QuadPart);
printf("Mutex: %d CritSec: %d\n", totalTime, totalTimeCS);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment