我嘗試學習大中央調度(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塊只是爲了確保工作流程是正確的,我相信它與性能無關。 –