我开发了一个用于多线程计算的类,线程只使用这个类的一个实例。此外,我想通过从另一个线程迭代此类的容器来测量计算的持续时间。应用程序是win32。事情是我读过 QueryPerformanceCounter 在比较单个线程上的测量值时很有用。因为我的问题不能使用它,所以我想到了clock() 或GetSystemTime()。遗憾的是,这两种方法的“分辨率”都是毫秒(因为在 win32 上 CLOCKS_PER_SEC 为 1000)。我应该使用或概括哪种方法,有更好的选择吗?作为一项规则,我必须在工作线程之外进行测量。这是一些代码作为示例。
unsinged long GetCounter()
{
SYSTEMTIME ww;
GetSystemTime(&ww);
return ww.wMilliseconds + 1000 * ww.wSeconds;
// or
return clock();
}
class WorkClass
{
bool is_working;
unsigned long counter;
HANDLE threadHandle;
public:
DoWork()
{
threadHandle = GetCurrentThread();
is_working = true;
counter = GetCounter();
// Do some work
is_working = false;
}
};
void CheckDurations() // will work on another thread;
{
for(size_t i =0;i < vector_of_workClass.size(); ++i)
{
WorkClass & wc = vector_of_workClass[i];
if(wc.is_working)
{
unsigned long dur = GetCounter() - wc.counter;
ReportDuration(wc,dur);
if( dur > someLimitValue)
TerminateThread(wc.threadHandle);
}
}
}