我必须使用 8 个处理器。 我想按如下方式进行并行调整大小:
vector<vector <int> > test;
test.resize(10000);
#pragma omp parallel num_threads(8)
{
#pragma omp for
for (int i = 0;i < 10000;i++)test[i].resize(500000);
}
我注意到该程序并没有使用 100% 的处理器能力——它只使用了 15%。当我更改代码时
vector<vector <int> > test;
test.resize(1000000);
#pragma omp parallel num_threads(8)
{
#pragma omp for
for (int i = 0;i < 1000000;i++)test[i].resize(5000);
}
程序使用了大约 60% 的处理器能力。我不明白这种现象——我希望它在这两种情况下都能使用 100% 的处理器能力。我在这里遗漏了什么吗?
最佳答案
在 Windows 上,CRT 使用内置的 Windows 堆实现,它是单线程的。
HeapAlloc在分配期间锁定一个 CriticalSection(本质上是一个互斥体),本质上是顺序分配过程。
由于 vector 大小调整主要是堆(重新)分配,因此并行化不会带来太大改进。
Serialization ensures mutual exclusion when two or more threads attempt to simultaneously allocate or free blocks from the same heap.
Setting the
HEAP_NO_SERIALIZE
value eliminates mutual exclusion on the heap. Without serialization, two or more threads that use the same heap handle might attempt to allocate or free memory simultaneously, likely causing corruption in the heap.
要从并行内存分配中获益,请使用不同的堆分配器。例如jemalloc .
关于c++ - 并行 vector 调整大小不加速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54576576/