CUDA Samples: Streams' usage
生活随笔
收集整理的這篇文章主要介紹了
CUDA Samples: Streams' usage
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
以下CUDA sample是分別用C++和CUDA實(shí)現(xiàn)的流的使用code,并對(duì)其中使用到的CUDA函數(shù)進(jìn)行了解說,code參考了《GPU高性能編程CUDA實(shí)戰(zhàn)》一書的第十章,各個(gè)文件內(nèi)容如下:
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__: 函數(shù)類型限定符;在設(shè)備上運(yùn)行;在主機(jī)端調(diào)用,計(jì)算能力3.2及以上可以在
設(shè)備端調(diào)用;聲明的函數(shù)的返回值必須是void類型;對(duì)此類型函數(shù)的調(diào)用是異步的,即在
設(shè)備完全完成它的運(yùn)行之前就返回了;對(duì)此類型函數(shù)的調(diào)用必須指定執(zhí)行配置,即用于在
設(shè)備上執(zhí)行函數(shù)時(shí)的grid和block的維度,以及相關(guān)的流(即插入<<< >>>運(yùn)算符);
a kernel,表示此函數(shù)為內(nèi)核函數(shù)(運(yùn)行在GPU上的CUDA并行計(jì)算函數(shù)稱為kernel(內(nèi)核函
數(shù)),內(nèi)核函數(shù)必須通過__global__函數(shù)類型限定符定義); */
__global__ static void stream_kernel(int* a, int* b, int* c, int length)
{/* gridDim: 內(nèi)置變量,用于描述線程網(wǎng)格的維度,對(duì)于所有線程塊來(lái)說,這個(gè)變量是一個(gè)常數(shù),用來(lái)保存線程格每一維的大小,即每個(gè)線程格中線程塊的數(shù)量.一個(gè)grid最多只有二維,為dim3類型;blockDim: 內(nèi)置變量,用于說明每個(gè)block的維度與尺寸.為dim3類型,包含了block在三個(gè)維度上的尺寸信息;對(duì)于所有線程塊來(lái)說,這個(gè)變量是一個(gè)常數(shù),保存的是線程塊中每一維的線程數(shù)量;blockIdx: 內(nèi)置變量,變量中包含的值就是當(dāng)前執(zhí)行設(shè)備代碼的線程塊的索引;用于說明當(dāng)前thread所在的block在整個(gè)grid中的位置,blockIdx.x取值范圍是[0,gridDim.x-1],blockIdx.y取值范圍是[0, gridDim.y-1].為uint3類型,包含了一個(gè)block在grid中各個(gè)維度上的索引信息;threadIdx: 內(nèi)置變量,變量中包含的值就是當(dāng)前執(zhí)行設(shè)備代碼的線程索引;用于說明當(dāng)前thread在block中的位置;如果線程是一維的可獲取threadIdx.x,如果是二維的還可獲取threadIdx.y,如果是三維的還可獲取threadIdx.z;為uint3類型,包含了一個(gè)thread在block中各個(gè)維度的索引信息 */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設(shè)備屬性結(jié)構(gòu)體cudaDeviceProp prop;// cudaGetDeviceProperties: 獲取GPU設(shè)備相關(guān)信息cudaGetDeviceProperties(&prop, 0);/* cudaDeviceProp::deviceOverlap: GPU是否支持設(shè)備重疊(Device Overlap)功能,支持設(shè)備重疊功能的GPU能夠在執(zhí)行一個(gè)CUDA C核函數(shù)的同時(shí),還能在設(shè)備與主機(jī)之間執(zhí)行復(fù)制等操作 */if (!prop.deviceOverlap) {printf("Device will not handle overlaps, so no speed up from streams\n");return -1;}/* cudaEvent_t: CUDA event types,結(jié)構(gòu)體類型, CUDA事件,用于測(cè)量GPU在某個(gè)任務(wù)上花費(fèi)的時(shí)間,CUDA中的事件本質(zhì)上是一個(gè)GPU時(shí)間戳,由于CUDA事件是在GPU上實(shí)現(xiàn)的,因此它們不適于對(duì)同時(shí)包含設(shè)備代碼和主機(jī)代碼的混合代碼計(jì)時(shí) */cudaEvent_t start, stop;// cudaEventCreate: 創(chuàng)建一個(gè)事件對(duì)象,異步啟動(dòng)cudaEventCreate(&start);cudaEventCreate(&stop);// cudaEventRecord: 記錄一個(gè)事件,異步啟動(dòng),start記錄起始時(shí)間cudaEventRecord(start, 0);/* cudaStream_t: cuda 流,結(jié)構(gòu)體類型, CUDA流表示一個(gè)GPU操作隊(duì)列,并且該隊(duì)列中的操作將以指定的順序執(zhí)行??梢詫⒚總€(gè)流視為GPU上的一個(gè)任務(wù),并且這些任務(wù)可以并行執(zhí)行。 */cudaStream_t stream;// cudaStreamCreate: 初始化流,創(chuàng)建一個(gè)新的異步流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: 在設(shè)備端分配內(nèi)存cudaMalloc(&dev_a, N * sizeof(int));cudaMalloc(&dev_b, N * sizeof(int));cudaMalloc(&dev_c, N * sizeof(int));/* cudaHostAlloc: 分配主機(jī)內(nèi)存(固定內(nèi)存)。C庫(kù)函數(shù)malloc將分配標(biāo)準(zhǔn)的,可分頁(yè)的(Pagable)主機(jī)內(nèi)存,而cudaHostAlloc將分配頁(yè)鎖定的主機(jī)內(nèi)存。頁(yè)鎖定內(nèi)存也稱為固定內(nèi)存(Pinned Memory)或者不可分頁(yè)內(nèi)存,它有一個(gè)重要的屬性:操作系統(tǒng)將不會(huì)對(duì)這塊內(nèi)存分頁(yè)并交換到磁盤上,從而確保了該內(nèi)存始終駐留在物理內(nèi)存中。因此,操作系統(tǒng)能夠安全地使某個(gè)應(yīng)用程序訪問該內(nèi)存的物理地址,因?yàn)檫@塊內(nèi)存將不會(huì)被破壞或者重新定位。由于GPU知道內(nèi)存的物理地址,因此可以通過"直接內(nèi)存訪問(Direct Memory Access, DMA)"技術(shù)來(lái)在GPU和主機(jī)之間復(fù)制數(shù)據(jù)。固定內(nèi)存是一把雙刃劍。當(dāng)使用固定內(nèi)存時(shí),你將失去虛擬內(nèi)存的所有功能。建議:僅對(duì)cudaMemcpy調(diào)用中的源內(nèi)存或者目標(biāo)內(nèi)存,才使用頁(yè)鎖定內(nèi)存,并且在不再需要使用它們時(shí)立即釋放。 */// 分配由流使用的頁(yè)鎖定內(nèi)存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與主機(jī)之間復(fù)制數(shù)據(jù)。cudaMemcpy的行為類似于C庫(kù)函數(shù)memcpy。尤其是,這個(gè)函數(shù)將以同步方式執(zhí)行,這意味著,當(dāng)函數(shù)返回時(shí),復(fù)制操作就已經(jīng)完成,并且在輸出緩沖區(qū)中包含了復(fù)制進(jìn)去的內(nèi)容。異步函數(shù)的行為與同步函數(shù)相反,在調(diào)用cudaMemcpyAsync時(shí),只是放置了一個(gè)請(qǐng)求,表示在流中執(zhí)行一次內(nèi)存復(fù)制操作,這個(gè)流是通過參數(shù)stream來(lái)指定的。當(dāng)函數(shù)返回時(shí),我們無(wú)法確保復(fù)制操作是否已經(jīng)啟動(dòng),更無(wú)法保證它們是否已經(jīng)結(jié)束。我們能夠得到的保證是,復(fù)制操作肯定會(huì)當(dāng)下一個(gè)被放入流中的操作之前執(zhí)行。任何傳遞給cudaMemcpyAsync的主機(jī)內(nèi)存指針都必須已經(jīng)通過cudaHostAlloc分配好內(nèi)存。也就是,你只能以異步方式對(duì)頁(yè)鎖定內(nèi)存進(jìn)行復(fù)制操作 */// 將鎖定內(nèi)存以異步方式復(fù)制到設(shè)備上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: 等待傳入流中的操作完成,主機(jī)在繼續(xù)執(zhí)行之前,要等待GPU執(zhí)行完成 */cudaStreamSynchronize(stream);//for (int i = 0; i < length; ++i)// c[i] = host_c[i];memcpy(c, host_c, length * sizeof(int));// cudaFreeHost: 釋放設(shè)備上由cudaHostAlloc函數(shù)分配的內(nèi)存cudaFreeHost(host_a);cudaFreeHost(host_b);cudaFreeHost(host_c);// cudaFree: 釋放設(shè)備上由cudaMalloc函數(shù)分配的內(nèi)存cudaFree(dev_a);cudaFree(dev_b);cudaFree(dev_c);// cudaStreamDestroy: 銷毀流cudaStreamDestroy(stream);// cudaEventRecord: 記錄一個(gè)事件,異步啟動(dòng),stop記錄結(jié)束時(shí)間cudaEventRecord(stop, 0);// cudaEventSynchronize: 事件同步,等待一個(gè)事件完成,異步啟動(dòng)cudaEventSynchronize(stop);// cudaEventElapseTime: 計(jì)算兩個(gè)事件之間經(jīng)歷的時(shí)間,單位為毫秒,異步啟動(dòng)cudaEventElapsedTime(elapsed_time, start, stop);// cudaEventDestroy: 銷毀事件對(duì)象,異步啟動(dòng)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);// 推薦采用寬度優(yōu)先方式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); // 使用單個(gè)流ret = streams_gpu_2(a, b, c, length, elapsed_time); // 使用多個(gè)流return ret;
}
執(zhí)行結(jié)果如下:可見使用C++和CUDA實(shí)現(xiàn)的結(jié)果是完全一致的:
GitHub:https://github.com/fengbingchun/CUDA_Test
總結(jié)
以上是生活随笔為你收集整理的CUDA Samples: Streams' usage的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CUDA Samples: Calcul
- 下一篇: CUDA Samples: dot pr