The Stopwatch class in C # is based on these two Win32 API calls that you can call from C / C ++:
Call the first function and divide it into the second function to get the value in seconds.
Example:
LARGE_INTEGER freq, start, end; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&start); // do some long operation here Sleep(5000); QueryPerformanceCounter(&end); // subtract before dividing to improve precision double durationInSeconds = static_cast<double>(end.QuadPart - start.QuadPart) / freq.QuadPart;
Please note that the following comment in the documentation is real and should be considered. I personally observed this behavior on the VirtualBox virtual machine. Differences in tens of milliseconds can exist between different processors, which leads to unexpected results, such as negative duration and duration exceeding expected:
On a multiprocessor computer, it should not matter which processor is called. However, you may get different results on different processors due to errors in the basic input / output system (BIOS) or hardware abstraction layer (HAL). To indicate the affinity of a processor for a thread, use the SetThreadAffinityMask function.
You may be interested in this for more: System.Diagnostics.Stopwatch returns negative numbers in Elapsed properties ...
Note that the Stopwatch class returns to GetTickCount if the above two APIs are not available or return failure codes. Most likely, it is just compatible with Windows 9x; I did not encounter any problems with these APIs on modern computers. However, GetTickCount will not have accurate accuracy.
source share