1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include <helper_cuda.h>
using namespace std;
__global__ void add_kernel(int a,int b, int *c) {
*c = a + b;
}
int main(void)
{
cudaError_t err = cudaSuccess;
////参数传递
int c;
int *dev_c;
err = cudaMalloc((void**)&dev_c, sizeof(int));
add_kernel << <1, 1 >> > (2, 7, dev_c); ////核函数处理
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device value dev_c (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaMemcpy(&c, dev_c, sizeof(int), cudaMemcpyDeviceToHost); ////主机代码中,不能对cudaMalloc()返回的指针进行读取,写入内存操作(即不可修改),但可以作参数传递,执行算术运算。
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy device value dev_c to c (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
printf("2+7=%d\n", c);
cudaFree(dev_c); ////不可使用free(),因为在主机代码中不可修改该内存的值 , 总的来说,主机指针只能访问主机代码的内存,设备指针只能访问设备代码的内存
////查询设备
cudaDeviceProp prop;
int count;
err = cudaGetDeviceCount(&count);
for (int i = 0; i < count; i++)
{
err = cudaGetDeviceProperties(&prop, i);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to get device %d properties (error code %s)!\n", i, cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
printf("Name: %s\n", prop.name);////这里打印设备信息,具体包含哪些信息查看《NVIDIA CUDA Programming Guide》
printf("Compute capability: %d . %d\n", prop.major,prop.minor);
printf("Total global Mem:%lld\n", prop.totalGlobalMem);
printf("Total constant Mem:%ld\n", prop.totalConstMem);
}
return 0;
}
|