我尝试学习大中央调度(GCD),并使用下面的代码进行测试:为什么GCD增加执行时间?
随着GCD:
#include <dispatch/dispatch.h>
#include <vector>
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[])
{
const int N = atoi(argv[1]);
__block std::vector<int> a(N, 0);
dispatch_apply(N,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^(size_t i)
{
a[i] = i;
#ifdef DEBUG
if (i % atoi(argv[2]) == 0)
std::cout << a[i] << std::endl;
#endif
});
return 0;
}
没有GCD:
#include <vector>
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[])
{
const int N = atoi(argv[1]);
std::vector<int> a(N, 0);
for (int i = 0; i < N; i++)
{
a[i] = i;
#ifdef DEBUG
if (i % atoi(argv[2]) == 0)
std::cout << a[i] << std::endl;
#endif
}
return 0;
}
与GCD的测试结果:
$ time ./testgcd 100000000 10000000
4.254 secs
没有GCD的测试:
$ time ./nogcd 100000000 10000000
1.462 secs
我认为GCD应该减少执行时间,但结果却表明相反。 我不确定我是否滥用GCD。 OS环境是带有Xcode 4.5的Mac OS X 10.8。编译器是Clang ++ 3.1。 硬件是MacBook Pro与i5 CPU,它有两个核心。
为了比较,我使用的OpenMP(也使用在Xcode 4.5在相同的膝上型计算机随附GCC):
#include <vector>
#include <cstdlib>
int main(int argc, char *argv[])
{
const int N = atoi(argv[1]);
std::vector <int> a(N, 0);
#pragma omp parallel for
for (int i = 0; i < N; i++)
a[i] = i;
return 0;
}
和W/W0(-fopenmp),我有两个可执行测试,
与-fopenmp
标志在编译:
$ time ./testopenmp 100000000
1.280 secs
没有-fopenmp
标志在编译:
$ time ./testnoopenmp 100000000
1.626 secs
使用OpenMP,执行时间减少。
想必您还没有为这些基准定义'#DEBUG'? –
DEBUG块只是为了确保工作流程是正确的,我相信它与性能无关。 –