为什么相同的向量v1
(正常情况下)和v2
(带有std::execution:parallel)对于v1
花费的时间较少,而对于v2
花费的时间较多?
我原以为并行排序会更快完成。
#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>
#include <execution>
using namespace std;
int main() {
// Generate identical vectors v1 and v2 of length N
// and fill them with v[i] = i/200;
int N = 10000;
vector<int> v1(N);
for(int i=0; i<N; i++) v1[i] = i/200;
auto v2 = v1;
// Calculate the time taken to sort in serial way.
auto start = std::chrono::system_clock::now();
sort(v1.begin(), v1.end());
auto end = std::chrono::system_clock::now();
auto diff = end - start;
cout << diff.count() << " = serial count" << endl;
// Calculate the time taken to sort in parallel way using
// std::execution::par
start = std::chrono::system_clock::now();
sort(std::execution::par, v2.begin(), v2.end());
end = std::chrono::system_clock::now();
diff = end - start;
cout << diff.count() << " = parallel parallel" << endl;
return 0;
}
结果:
626600 = serial count
1048100 = parallel count
1条答案
按热度按时间vq8itlhq1#
int N = 10000;
包含的元素太少了。运行和等待线程完成的开销可能会超过使用如此少量元素的串行运行时间。无论如何,我在www.example.com上得到了其他结果onlinegdb.com(使用-O2):