我试图理解为什么增加线程数(在一定数量之后)会增加而不是减少 CPU 时间。
代码功能的总结:我有一个 main,它根据维度创建一个大向量。我用索引(0..dimension-1)填充它,然后对其进行洗牌。然后,为了进行分而治之,我对该向量进行分区,为每个线程提供一个切片。我准备了一个由解决方案向量组成的向量,将每个条目提供给线程。每个线程在其切片的每个元素上调用一个函数,并将引用传递给其准备好的解决方案。该函数只是更改输入中给定索引处的解决方案的值,然后它只是增加解决方案中的所有元素(我将其稍微增加了计算时间)。这里是代码:
#include <algorithm>
#include <random>
#include <thread>
#include <iostream>
#include <chrono>
#include <vector>
#include <numeric>
using namespace std;
template<typename T>
inline double getMs(T start, T end) {
return double(
std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
.count()) /
1000;
}
void fun(const std::vector<int>& slice, int dimension,
vector<int>& internal_sol) {
int size = dimension;
for (auto const& s : slice) {
internal_sol[s] = 45;
internal_sol[int(s/2)] = 45;
if (s != 0) {
internal_sol[s - 1] = 45;
}
if (s != …Run Code Online (Sandbox Code Playgroud)