【发布时间】:2019-10-03 20:22:42
【问题描述】:
我想测量一些代码的执行时间。代码从 main() 函数开始,在事件处理程序中结束。
我的 C++11 代码如下所示:
#include <iostream>
#include <time.h>
...
volatile clock_t t;
void EventHandler()
{
// when this function called is the end of the part that I want to measure
t = clock() - t;
std::cout << "time in seconds: " << ((float)t)/CLOCKS_PER_SEC;
}
int main()
{
MyClass* instance = new MyClass(EventHandler); // this function starts a new std::thread
instance->start(...); // this function only passes some data to the thread working data, later the thread will call EventHandler()
t = clock();
return 0;
}
因此可以保证 EventHandler() 只会被调用一次,并且只会在 instance->start() 调用之后。
它正在工作,这段代码给了我一些输出,但它是一个可怕的代码,它使用全局变量并且不同的线程访问全局变量。但是我无法更改使用的 API(构造函数,线程调用 EventHandler 的方式)。
我想问是否有更好的解决方案。
谢谢。
【问题讨论】:
-
仅供参考:易失性不是原子的,如果这完全可行,那基本上是运气。
-
这里有一个种族问题。如果工作线程足够快,
EventHandler可能会在首次初始化t之前被调用...您最好不要尝试跨线程时间测量。这只是随机的。
标签: c++ multithreading time measure