测量上下文切换时间 C (Windows)
我需要实现一种方法,可以测量 Windows 中线程之间上下文切换的时间和 CPU 周期。
这是我的代码
#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;
}
注意:除以二是因为我在initialTimeStamp和finalTimeStamp之间有两个上下文切换。
我不知道这是否是最好或正确的方法...每次执行我都会得到不同的时间,这不是我所期望的。 我不知道如何获得 CPU 周期数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,您必须有一个正在消耗 CPU 周期的线程才能让 SwitchToThread() 真正进行上下文切换。如果您的 CPU 有多个核心,则不止一个。即便如此,你得到的结果在很大程度上也是毫无意义的。开销量变化很大,具体取决于拥有获取量程的线程的进程和 TLB 缓存的状态。重新加载 TLB 寄存器和获取缓存未命中会增加大量时间。通常的循环次数在 2,000 到 10,000 次之间。
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.
由于计算机性能变化很大,因此您的时间会有所不同。
You are getting different times because computer performance is very variable.