#include <stdio.h> #include <cuda.h> // Kernel that executes on the CUDA device __global__ void square_array(float *a, int N) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx<N) a[idx] = a[idx] * a[idx]; } int main() { float *a_h, *a_d; // Pointer to host & device arrays const int N = 10; // Number of elements in arrays size_t size = N * sizeof(float); a_h = (float *)malloc(size); // Allocate array on host cudaMalloc((void **) &a_d, size); // Allocate array on device // Initialize host array and copy it to CUDA device for (int i=0; i<N; i++) a_h[i] = (float)i; cudaMemcpy(a_d, a_h, size, cudaMemcpyHostToDevice); // Do calculation on device: int block_size = 32; int n_blocks = N/block_size + (N%block_size == 0 ? 0:1); square_array <<< n_blocks, block_size >>> (a_d, N); // Retrieve result from device and store it in host array cudaMemcpy(a_h, a_d, sizeof(float)*N, cudaMemcpyDeviceToHost); // Print results for (int i=0; i<N; i++) printf("%d %f\n", i, a_h[i]); // Cleanup free(a_h); cudaFree(a_d); return 0; }
时间: 2024-03-31 15:38:49 浏览: 25
这段代码是一个简单的 CUDA 程序,它使用 GPU 加速了一个数组元素的平方计算。程序首先在 CPU 上分配了一个大小为 N 的浮点数数组 a_h,并初始化为 0 到 N-1 的整数。然后,它在 GPU 上分配了一个与 a_h 相同大小的浮点数数组 a_d,并将 a_h 的数据复制到 a_d。接下来,程序定义了一个名为 square_array 的 GPU 内核函数,该函数将执行实际的计算。此内核函数采用两个参数:指向 a_d 数组的指针和数组大小 N。在内核函数中,每个线程根据其在线程块中的索引和线程块的索引计算其在 a_d 数组中的索引,并将该位置的元素平方。最后,程序从 GPU 将计算结果复制回 a_h 数组,并打印出所有元素的平方值。
值得注意的是,要使用 CUDA 进行 GPU 编程,需要安装 CUDA 工具包并使用适当的编译器和链接器来构建程序。此外,还需要理解 GPU 内核函数和线程块之间的映射关系,以及如何管理内存和数据传输。
相关问题
#include<stdio.h>和 #include "stdio.h" 有啥区别
在C语言中,#include是一个预处理指令,用于在编译程序之前将指定的头文件包含到源代码中。其中,#include <stdio.h>和#include "stdio.h"都是用来包含头文件<stdio.h>的指令。但它们有以下几点区别:
1. #include <stdio.h>是从系统目录中查找头文件,而#include "stdio.h"是从当前目录中查找头文件。
2. 如果在当前目录和系统目录中都存在同名的头文件,则#include "stdio.h"会优先使用当前目录中的头文件,而#include <stdio.h>则会使用系统目录中的头文件。
3. 如果使用了编译器的特殊选项,如-I选项,指定了头文件的搜索路径,则#include <stdio.h>会在指定的路径中查找头文件,而#include "stdio.h"仍然会在当前目录中查找头文件。
综上所述,#include <stdio.h>和#include "stdio.h"的主要区别在于它们查找头文件的方式不同。如果你需要包含C标准库的头文件,则通常使用#include <stdio.h>;如果你需要包含自己编写的头文件,则通常使用#include "stdio.h"。
#include <corecrt_math_defines.h> #include <stdio.h>
#include <corecrt_math_defines.h> 是C语言中的一个头文件,它定义了一些数学常量,例如圆周率π和自然对数的底数e等。这个头文件是为了方便在程序中使用这些常量而引入的。
而 #include <stdio.h> 是C语言中的另一个头文件,它包含了一些输入输出函数的声明,例如printf和scanf等。这个头文件是为了方便在程序中进行输入输出操作而引入的。
这两个头文件都是C语言标准库中的一部分,可以在C语言程序中使用。它们提供了一些常用的功能和工具,可以帮助开发者更方便地编写程序。