CUDA Samples: Streams' usage
生活随笔
收集整理的這篇文章主要介紹了
CUDA Samples: Streams' usage
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
以下CUDA sample是分別用C++和CUDA實現的流的使用code,并對其中使用到的CUDA函數進行了解說,code參考了《GPU高性能編程CUDA實戰》一書的第十章,各個文件內容如下:
funset.cpp:
#include "funset.hpp"
#include <random>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <algorithm>
#include "common.hpp"
#include <opencv2/opencv.hpp>int test_streams()
{const int length{ 1024 * 1024 * 20};std::unique_ptr<int[]> A(new int[length]);std::unique_ptr<int[]> B(new int[length]);std::unique_ptr<int[]> C1(new int[length]);std::unique_ptr<int[]> C2(new int[length]);generator_random_number<int>(A.get(), length, -100, 100);generator_random_number<int>(B.get(), length, -100, 100);std::for_each(C1.get(), C1.get() + length, [](int& n) {n = 0; });std::for_each(C2.get(), C2.get() + length, [](int& n) {n = 0; });float elapsed_time1{ 0.f }, elapsed_time2{ 0.f }; // millisecondsint ret = streams_cpu(A.get(), B.get(), C1.get(), length, &elapsed_time1);if (ret != 0) PRINT_ERROR_INFO(streams_cpu);ret = streams_gpu(A.get(), B.get(), C2.get(), length, &elapsed_time2);if (ret != 0) PRINT_ERROR_INFO(streams_gpu);for (int i = 0; i < length; ++i) {if (C1[i] != C2[i]) {fprintf(stderr, "their values are different at: %d, val1: %d, val2: %d\n",i, C1[i], C2[i]);return -1;}}fprintf(stderr, "test streams' usage: cpu run time: %f ms, gpu run time: %f ms\n", elapsed_time1, elapsed_time2);return 0;
}
streams.cpp:
#include "funset.hpp"
#include <chrono>int streams_cpu(const int* a, const int* b, int* c, int length, float* elapsed_time)
{auto start = std::chrono::steady_clock::now();const int N{ length / 20 };for (int x = 0; x < 20; ++x) {const int* pa = a + x * N;const int* pb = b + x * N;int* pc = c + x * N;for (int idx = 0; idx < N; ++idx) {int idx1 = (idx + 1) % 256;int idx2 = (idx + 2) % 256;float as = (pa[idx] + pa[idx1] + pa[idx2]) / 3.0f;float bs = (pb[idx] + pb[idx1] + pb[idx2]) / 3.0f;pc[idx] = (as + bs) / 2;}}auto end = std::chrono::steady_clock::now();auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);*elapsed_time = duration.count() * 1.0e-6;return 0;
}
streams.cu:
#include "funset.hpp"
#include <iostream>
#include <algorithm>
#include <memory>
#include <vector>
#include <cuda_runtime.h> // For the CUDA runtime routines (prefixed with "cuda_")
#include <device_launch_parameters.h>
#include "common.hpp"/* __global__: 函數類型限定符;在設備上運行;在主機端調用,計算能力3.2及以上可以在
設備端調用;聲明的函數的返回值必須是void類型;對此類型函數的調用是異步的,即在
設備完全完成它的運行之前就返回了;對此類型函數的調用必須指定執行配置,即用于在
設備上執行函數時的grid和block的維度,以及相關的流(即插入<<< >>>運算符);
a kernel,表示此函數為內核函數(運行在GPU上的CUDA并行計算函數稱為kernel(內核函
數),內核函數必須通過__global__函數類型限定符定義); */
__global__ static void stream_kernel(int* a, int* b, int* c, int length)
{/* gridDim: 內置變量,用于描述線程網格的維度,對于所有線程塊來說,這個變量是一個常數,用來保存線程格每一維的大小,即每個線程格中線程塊的數量.一個grid最多只有二維,為dim3類型;blockDim: 內置變量,用于說明每個block的維度與尺寸.為dim3類型,包含了block在三個維度上的尺寸信息;對于所有線程塊來說,這個變量是一個常數,保存的是線程塊中每一維的線程數量;blockIdx: 內置變量,變量中包含的值就是當前執行設備代碼的線程塊的索引;用于說明當前thread所在的block在整個grid中的位置,blockIdx.x取值范圍是[0,gridDim.x-1],blockIdx.y取值范圍是[0, gridDim.y-1].為uint3類型,包含了一個block在grid中各個維度上的索引信息;threadIdx: 內置變量,變量中包含的值就是當前執行設備代碼的線程索引;用于說明當前thread在block中的位置;如果線程是一維的可獲取threadIdx.x,如果是二維的還可獲取threadIdx.y,如果是三維的還可獲取threadIdx.z;為uint3類型,包含了一個thread在block中各個維度的索引信息 */int idx = threadIdx.x + blockIdx.x * blockDim.x;if (idx < length) {int idx1 = (idx + 1) % 256;int idx2 = (idx + 2) % 256;float as = (a[idx] + a[idx1] + a[idx2]) / 3.0f;float bs = (b[idx] + b[idx1] + b[idx2]) / 3.0f;c[idx] = (as + bs) / 2;}
}int streams_gpu_1(const int* a, const int* b, int* c, int length, float* elapsed_time)
{// cudaDeviceProp: cuda設備屬性結構體cudaDeviceProp prop;// cudaGetDeviceProperties: 獲取GPU設備相關信息cudaGetDeviceProperties(&prop, 0);/* cudaDeviceProp::deviceOverlap: GPU是否支持設備重疊(Device Overlap)功能,支持設備重疊功能的GPU能夠在執行一個CUDA C核函數的同時,還能在設備與主機之間執行復制等操作 */if (!prop.deviceOverlap) {printf("Device will not handle overlaps, so no speed up from streams\n");return -1;}/* cudaEvent_t: CUDA event types,結構體類型, CUDA事件,用于測量GPU在某個任務上花費的時間,CUDA中的事件本質上是一個GPU時間戳,由于CUDA事件是在GPU上實現的,因此它們不適于對同時包含設備代碼和主機代碼的混合代碼計時 */cudaEvent_t start, stop;// cudaEventCreate: 創建一個事件對象,異步啟動cudaEventCreate(&start);cudaEventCreate(&stop);// cudaEventRecord: 記錄一個事件,異步啟動,start記錄起始時間cudaEventRecord(start, 0);/* cudaStream_t: cuda 流,結構體類型, CUDA流表示一個GPU操作隊列,并且該隊列中的操作將以指定的順序執行??梢詫⒚總€流視為GPU上的一個任務,并且這些任務可以并行執行。 */cudaStream_t stream;// cudaStreamCreate: 初始化流,創建一個新的異步流cudaStreamCreate(&stream);int *host_a{ nullptr }, *host_b{ nullptr }, *host_c{ nullptr };int *dev_a{ nullptr }, *dev_b{ nullptr }, *dev_c{ nullptr };const int N{ length / 20 };// cudaMalloc: 在設備端分配內存cudaMalloc(&dev_a, N * sizeof(int));cudaMalloc(&dev_b, N * sizeof(int));cudaMalloc(&dev_c, N * sizeof(int));/* cudaHostAlloc: 分配主機內存(固定內存)。C庫函數malloc將分配標準的,可分頁的(Pagable)主機內存,而cudaHostAlloc將分配頁鎖定的主機內存。頁鎖定內存也稱為固定內存(Pinned Memory)或者不可分頁內存,它有一個重要的屬性:操作系統將不會對這塊內存分頁并交換到磁盤上,從而確保了該內存始終駐留在物理內存中。因此,操作系統能夠安全地使某個應用程序訪問該內存的物理地址,因為這塊內存將不會被破壞或者重新定位。由于GPU知道內存的物理地址,因此可以通過"直接內存訪問(Direct Memory Access, DMA)"技術來在GPU和主機之間復制數據。固定內存是一把雙刃劍。當使用固定內存時,你將失去虛擬內存的所有功能。建議:僅對cudaMemcpy調用中的源內存或者目標內存,才使用頁鎖定內存,并且在不再需要使用它們時立即釋放。 */// 分配由流使用的頁鎖定內存cudaHostAlloc(&host_a, length * sizeof(int), cudaHostAllocDefault);cudaHostAlloc(&host_b, length * sizeof(int), cudaHostAllocDefault);cudaHostAlloc(&host_c, length * sizeof(int), cudaHostAllocDefault);//for (int i = 0; i < length; ++i) {// host_a[i] = a[i];// host_b[i] = b[i];//}memcpy(host_a, a, length * sizeof(int));memcpy(host_b, b, length * sizeof(int));for (int i = 0; i < length; i += N) {/* cudaMemcpyAsync: 在GPU與主機之間復制數據。cudaMemcpy的行為類似于C庫函數memcpy。尤其是,這個函數將以同步方式執行,這意味著,當函數返回時,復制操作就已經完成,并且在輸出緩沖區中包含了復制進去的內容。異步函數的行為與同步函數相反,在調用cudaMemcpyAsync時,只是放置了一個請求,表示在流中執行一次內存復制操作,這個流是通過參數stream來指定的。當函數返回時,我們無法確保復制操作是否已經啟動,更無法保證它們是否已經結束。我們能夠得到的保證是,復制操作肯定會當下一個被放入流中的操作之前執行。任何傳遞給cudaMemcpyAsync的主機內存指針都必須已經通過cudaHostAlloc分配好內存。也就是,你只能以異步方式對頁鎖定內存進行復制操作 */// 將鎖定內存以異步方式復制到設備上cudaMemcpyAsync(dev_a, host_a + i, N * sizeof(int), cudaMemcpyHostToDevice, stream);cudaMemcpyAsync(dev_b, host_b + i, N * sizeof(int), cudaMemcpyHostToDevice, stream);stream_kernel << <N / 256, 256, 0, stream >> >(dev_a, dev_b, dev_c, N);cudaMemcpyAsync(host_c + i, dev_c, N * sizeof(int), cudaMemcpyDeviceToHost, stream);}/* cudaStreamSynchronize: 等待傳入流中的操作完成,主機在繼續執行之前,要等待GPU執行完成 */cudaStreamSynchronize(stream);//for (int i = 0; i < length; ++i)// c[i] = host_c[i];memcpy(c, host_c, length * sizeof(int));// cudaFreeHost: 釋放設備上由cudaHostAlloc函數分配的內存cudaFreeHost(host_a);cudaFreeHost(host_b);cudaFreeHost(host_c);// cudaFree: 釋放設備上由cudaMalloc函數分配的內存cudaFree(dev_a);cudaFree(dev_b);cudaFree(dev_c);// cudaStreamDestroy: 銷毀流cudaStreamDestroy(stream);// cudaEventRecord: 記錄一個事件,異步啟動,stop記錄結束時間cudaEventRecord(stop, 0);// cudaEventSynchronize: 事件同步,等待一個事件完成,異步啟動cudaEventSynchronize(stop);// cudaEventElapseTime: 計算兩個事件之間經歷的時間,單位為毫秒,異步啟動cudaEventElapsedTime(elapsed_time, start, stop);// cudaEventDestroy: 銷毀事件對象,異步啟動cudaEventDestroy(start);cudaEventDestroy(stop);return 0;
}int streams_gpu_2(const int* a, const int* b, int* c, int length, float* elapsed_time)
{cudaDeviceProp prop;cudaGetDeviceProperties(&prop, 0);if (!prop.deviceOverlap) {printf("Device will not handle overlaps, so no speed up from streams\n");return -1;}cudaEvent_t start, stop;cudaEventCreate(&start);cudaEventCreate(&stop);cudaEventRecord(start, 0);cudaStream_t stream0, stream1;cudaStreamCreate(&stream0);cudaStreamCreate(&stream1);int *host_a{ nullptr }, *host_b{ nullptr }, *host_c{ nullptr };int *dev_a0{ nullptr }, *dev_b0{ nullptr }, *dev_c0{ nullptr };int *dev_a1{ nullptr }, *dev_b1{ nullptr }, *dev_c1{ nullptr };const int N{ length / 20 };cudaMalloc(&dev_a0, N * sizeof(int));cudaMalloc(&dev_b0, N * sizeof(int));cudaMalloc(&dev_c0, N * sizeof(int));cudaMalloc(&dev_a1, N * sizeof(int));cudaMalloc(&dev_b1, N * sizeof(int));cudaMalloc(&dev_c1, N * sizeof(int));cudaHostAlloc(&host_a, length * sizeof(int), cudaHostAllocDefault);cudaHostAlloc(&host_b, length * sizeof(int), cudaHostAllocDefault);cudaHostAlloc(&host_c, length * sizeof(int), cudaHostAllocDefault);memcpy(host_a, a, length * sizeof(int));memcpy(host_b, b, length * sizeof(int));for (int i = 0; i < length; i += N * 2) {//cudaMemcpyAsync(dev_a0, host_a + i, N * sizeof(int), cudaMemcpyHostToDevice, stream0);//cudaMemcpyAsync(dev_b0, host_b + i, N * sizeof(int), cudaMemcpyHostToDevice, stream0);//stream_kernel << <N / 256, 256, 0, stream0 >> >(dev_a0, dev_b0, dev_c0, N);//cudaMemcpyAsync(host_c + i, dev_c0, N * sizeof(int), cudaMemcpyDeviceToHost, stream0);//cudaMemcpyAsync(dev_a1, host_a + i + N, N * sizeof(int), cudaMemcpyHostToDevice, stream1);//cudaMemcpyAsync(dev_b1, host_b + i + N, N * sizeof(int), cudaMemcpyHostToDevice, stream1);//stream_kernel << <N / 256, 256, 0, stream1 >> >(dev_a1, dev_b1, dev_c1, N);//cudaMemcpyAsync(host_c + i + N, dev_c1, N * sizeof(int), cudaMemcpyDeviceToHost, stream1);// 推薦采用寬度優先方式cudaMemcpyAsync(dev_a0, host_a + i, N * sizeof(int), cudaMemcpyHostToDevice, stream0);cudaMemcpyAsync(dev_a1, host_a + i + N, N * sizeof(int), cudaMemcpyHostToDevice, stream1);cudaMemcpyAsync(dev_b0, host_b + i, N * sizeof(int), cudaMemcpyHostToDevice, stream0);cudaMemcpyAsync(dev_b1, host_b + i + N, N * sizeof(int), cudaMemcpyHostToDevice, stream1);stream_kernel << <N / 256, 256, 0, stream0 >> >(dev_a0, dev_b0, dev_c0, N);stream_kernel << <N / 256, 256, 0, stream1 >> >(dev_a1, dev_b1, dev_c1, N);cudaMemcpyAsync(host_c + i, dev_c0, N * sizeof(int), cudaMemcpyDeviceToHost, stream0);cudaMemcpyAsync(host_c + i + N, dev_c1, N * sizeof(int), cudaMemcpyDeviceToHost, stream1);}cudaStreamSynchronize(stream0);cudaStreamSynchronize(stream1);memcpy(c, host_c, length * sizeof(int));cudaFreeHost(host_a);cudaFreeHost(host_b);cudaFreeHost(host_c);cudaFree(dev_a0);cudaFree(dev_b0);cudaFree(dev_c0);cudaFree(dev_a1);cudaFree(dev_b1);cudaFree(dev_c1);cudaStreamDestroy(stream0);cudaStreamDestroy(stream1);cudaEventRecord(stop, 0);cudaEventSynchronize(stop);cudaEventElapsedTime(elapsed_time, start, stop);cudaEventDestroy(start);cudaEventDestroy(stop);return 0;
}int streams_gpu(const int* a, const int* b, int* c, int length, float* elapsed_time)
{int ret{ 0 };//ret = streams_gpu_1(a, b, c, length, elapsed_time); // 使用單個流ret = streams_gpu_2(a, b, c, length, elapsed_time); // 使用多個流return ret;
}
執行結果如下:可見使用C++和CUDA實現的結果是完全一致的:
GitHub:https://github.com/fengbingchun/CUDA_Test
總結
以上是生活随笔為你收集整理的CUDA Samples: Streams' usage的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CUDA Samples: Calcul
- 下一篇: CUDA Samples: dot pr