天天看點

項目優化之:GPU程式設計



1gpu程式設計,依賴于顯示卡

2gpu變成依賴于opengl和direct

3cpu的特點是:頻率比較快,gpu的特點是寄存器非常非常的多。

4如果電腦是windows7,沒法直接調試gpu。window8可以直接調試

5用vs2013建立一個項目,命名:gpu

6調試gpu的方式是vs中的:打斷點—>運作項目à調試à視窗àgpu線程(通過這種方式實作調試gpu項目)

8.修改項目屬性:右擊項目à屬性à配置屬性à正常,修改調試器類型為僅gpu

修改amp預設快捷鍵可以選擇時時(use

c++ amp runtime default)的方式,也可以使用軟體加速器(warpsoftware accelerator)的方式,截圖

項目優化之:GPU程式設計

9.代碼:

#include

<iostream>

<amp.h> 

//gpu程式設計所需的頭檔案

using

namespace

concurrency;

int

main()

{

v[11] = {

'g',

'd',

'k',

'n', 31,

'v',

'n',

'q',

'c' };

array_view<int>

av(11,

v);//array_view是gpu計算結構,av存儲到gpu顯存

//=表示直接操作av

//(index<1> idx)操作每一個元素

//restrict(amp)定位gpu執行

parallel_for_each(av.extent,

[=](index<1>

idx)

restrict(amp)

av[idx]

+= 1;//加完後變成了hello world

});

for (unsigned

i = 0;

i < 11;

i++)

std::cout

<< static_cast<char>(av[i]);

}

std::cin.get();

return 0;

項目優化之:GPU程式設計

10.cpu,gpu單值計算效率測試

案例:

<iostream> 

<amp.h>

<winbase.h>

#define

count 100000

float

nickname_gpu[count];

nickname_cpu[count];

//gpu并行計算比較占有優勢,restrict(amp):限制使用gpu程式設計

double

rungpu(int

num)

temp = 0;

for (int

i <

num;

temp +=

i;

return

temp;

//cpu處理單值計算比較有優勢,單點計算比較有優勢,隻能在gpu内部執行

runcpu(int

restrict(cpu)

//這是對一個數進行操作

//限制使用gpu或cpu運作

runcpugpu(int

restrict(amp,

cpu)

//測試單值計算的運作效率

large_integer

freq;

strt;

ed;

queryperformancefrequency(&freq);

queryperformancecounter(&strt);

dx[1] = { 0.0 };

double 

db = 0.0;

concurrency::array_view<double>

myview(1,

dx);

parallel_for_each(myview.extent,

[=](concurrency::index<1>

myview[idx]

+= rungpu(1000000);

myview.synchronize();//顯式等待gpu計算完成并将資料打回記憶體

printf("%f\n",

dx[0]);

queryperformancecounter(&ed);

printf("gpu耗時:

%d 毫秒\r\n", (ed.quadpart

- strt.quadpart)

* 1000 / freq.quadpart);

runcpu(1000000));

printf("cpu耗時:

puts("測試結束");

getchar();

運作結果:

項目優化之:GPU程式設計

案例2:

count 3000

double temp = 0;

temp += i;

return temp;

large_integer freq;

large_integer strt;

large_integer ed;

concurrency::array_view<float>

myview(count,

nickname_gpu);

//将資料打入顯存 

concurrency::parallel_for_each(myview.extent,

count / 10;

myview[idx] = (myview[idx]

+ 0.1f) / 2.3f;

myview.synchronize();//顯式等待gpu計算完成并将資料打回記憶體 

- strt.quadpart) * 1000 / freq.quadpart);

idx = 0; idx <

count; idx++)

nickname_cpu[idx] = (nickname_cpu[idx]

+ 0.1f) /2.3f;

if (nickname_cpu[idx]

!= nickname_gpu[idx])

puts("cpu和gpu的計算結果不相符!");

項目優化之:GPU程式設計