您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“CUDA計時器怎么實現(xiàn)”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
在進行CUDA編程時,需要利用計時方法查看程序運行速度。
首先給出頭文件 gputimer.h
#ifndef __GPU_TIMER_H__ #define __GPU_TIMER_H__ struct GpuTimer { cudaEvent_t start; cudaEvent_t stop; GpuTimer() { cudaEventCreate(&start); cudaEventCreate(&stop); } ~GpuTimer() { cudaEventDestroy(start); cudaEventDestroy(stop); } void Start() { cudaEventRecord(start, 0); } void Stop() { cudaEventRecord(stop, 0); } float Elapsed() { float elapsed; cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsed, start, stop); return elapsed; } }; #endif /* __GPU_TIMER_H__ */
通用用法
GpuTimer timer; timer.Start(); // launch the kernal kernal<<<1, ARRAY_SIZE>>>(d_out, d_in); timer.Stop(); printf("Time elapsed = %g ms\n", timer.Elapsed()); // 輸出
實際運用,計算1000個數(shù)的平方
#include <cuda_runtime.h> #include "device_launch_parameters.h" #include "gputimer.h" #include <stdio.h> #include <stdlib.h> __global__ void square(float* d_out, float* d_in) { int idx = threadIdx.x; float f = d_in[idx]; d_out[idx] = f * f; } int main() { GpuTimer timer; const int ARRAY_SIZE = 1000; const int ARRAY_BYTES = ARRAY_SIZE * sizeof(float); // generate the input array on the host float h_in[ARRAY_SIZE]; for (int i = 0; i < ARRAY_SIZE; i++) { h_in[i] = float(i); } float h_out[ARRAY_SIZE]; // declare GPU memory pointers float* d_in; float* d_out; // allocate GPU memory cudaMalloc((void **)&d_in, ARRAY_BYTES); cudaMalloc((void**)&d_out, ARRAY_BYTES); // transfer the array to the GPU cudaMemcpy(d_in, h_in, ARRAY_BYTES, cudaMemcpyHostToDevice); timer.Start(); // launch the kernal square<<<1, ARRAY_SIZE>>>(d_out, d_in); timer.Stop(); // copy back the result array to the CPU cudaMemcpy(h_out, d_out, ARRAY_BYTES, cudaMemcpyDeviceToHost); // print out the resulting array for (int i = 0; i < ARRAY_SIZE; i++) { printf("%f", h_out[i]); printf(((i % 4) != 3) ? "\t" : "\n"); } printf("Time elapsed = %g ms\n", timer.Elapsed()); // free GPU memory allocation cudaFree(d_in); cudaFree(d_out); system("pause"); return 0; }
運行結(jié)果:
“CUDA計時器怎么實現(xiàn)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。