我认为衡量开销的方法是对串行和并行版本进行计时,然后查看并行版本与线程数的“理想”运行时间相差多远。
例如,如果您的串行版本需要 10 秒,并且您在 4 个内核上有 4 个线程,那么您的理想运行时间是 2.5 秒。如果您的 OpenMP 版本需要 4 秒,那么您的“开销”就是 1.5 秒。我将开销放在引号中,因为其中一些将是线程创建和内存共享(实际的线程开销),而其中一些将只是未并行的代码部分。我试图在这里思考阿姆达尔定律.
为了演示,这里有两个例子。它们不测量线程创建开销,但可能显示预期改进和实现改进之间的差异。虽然神秘主义是正确的,唯一真正的衡量方法是计时,但即使是像你这样的微不足道的例子for
循环不一定受内存限制。 OpenMP 做了很多我们看不到的工作。
串行(速度测试.cpp)
#include <iostream>
int main(int argc, char** argv) {
const int SIZE = 100000000;
int* a = new int[SIZE];
int* b = new int[SIZE];
int* c = new int[SIZE];
for(int i = 0; i < SIZE; i++) {
a[i] = b[i] * c[i] * 2;
}
std::cout << "a[" << (SIZE-1) << "]=" << a[SIZE-1] << std::endl;
for(int i = 0; i < SIZE; i++) {
a[i] = b[i] + c[i] + 1;
}
std::cout << "a[" << (SIZE-1) << "]=" << a[SIZE-1] << std::endl;
delete[] a;
delete[] b;
delete[] c;
return 0;
}
并行(omp_speedtest.cpp)
#include <omp.h>
#include <iostream>
int main(int argc, char** argv) {
const int SIZE = 100000000;
int* a = new int[SIZE];
int* b = new int[SIZE];
int* c = new int[SIZE];
std::cout << "There are " << omp_get_num_procs() << " procs." << std::endl;
#pragma omp parallel
{
#pragma omp for
for(int i = 0; i < SIZE; i++) {
a[i] = b[i] * c[i];
}
}
std::cout << "a[" << (SIZE-1) << "]=" << a[SIZE-1] << std::endl;
#pragma omp parallel
{
#pragma omp for
for(int i = 0; i < SIZE; i++) {
a[i] = b[i] + c[i] + 1;
}
}
std::cout << "a[" << (SIZE-1) << "]=" << a[SIZE-1] << std::endl;
delete[] a;
delete[] b;
delete[] c;
return 0;
}
所以我用这些来编译这些
g++ -O3 -o speedtest.exe speedtest.cpp
g++ -fopenmp -O3 -o omp_speedtest.exe omp_speedtest.cpp
当我运行它们时
$ time ./speedtest.exe
a[99999999]=0
a[99999999]=1
real 0m1.379s
user 0m0.015s
sys 0m0.000s
$ time ./omp_speedtest.exe
There are 4 procs.
a[99999999]=0
a[99999999]=1
real 0m0.854s
user 0m0.015s
sys 0m0.015s