<分区>
假设我有一个类 Manager
做一些工作,然后我有一个 DistributedManager
,它继承自 Manager
但重新实现了一些使用多线程的方法。
使用它们的代码是
Manager<T,W,P> manager(initargs);
manager.compute(runargs);
或
DistributedManager<T,W,P> manager(initargs, 4); // 4 is number of thread to use
manager.compute(runargs);
然后在某些时候,我希望可以通过类似命令修改我使用的线程数。所以我制作了一个 size_t nbthread = 1
,它可以通过一个选项进行修改,我将我的代码修改为以下内容:
Manager<T,W,P>* manager;
switch(nbthread)
{
case 0:
case 1:
manager = new Manager<T,W,P>(initargs);
break;
default:
manager = new DistributedManager<T,W,P>(initargs, nbthread);
break;
}
manager->compute(runargs);
它可以编译并工作...但是我的表现很糟糕!
使用第一种方法和 DistributedManager
和 4 个线程我可以在 500 毫秒内运行,使用第二种方法相同的计算运行时间超过 2000 毫秒。
分配部分不应该那么长:
sizeof(Manager<T,W,P>) : 104
sizeof(DistributedManager<T,W,P>) : 128
出了什么问题?
编辑
基准测试使用
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
densityfieldptr->compute(particles, massfield, massthreshold, densityfunctor);
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
printf("computation time: %ld ms\n", std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count());
编辑2:我很蠢
时间增加了大约 4 倍……因为调用的是非多线程版本。使用指向基类的指针在使用这些方法的地方!
virtual
关键字不能用来解决这个问题,因为方法是模板化的
我不得不重新考虑我的模板模式,一切都按预期工作