le mie informazioni di contatto
Posta[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
#include <stdio.h>
// includes CUDA Runtime
#include <cuda_runtime.h>
#include <cuda_profiler_api.h>
// includes, project
#include <helper_cuda.h>
#include <helper_functions.h> // helper utility functions
__global__ void increment_kernel(int *g_data, int inc_value) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
g_data[idx] = g_data[idx] + inc_value;
}
bool correct_output(int *data, const int n, const int x) {
for (int i = 0; i < n; i++)
if (data[i] != x) {
printf("Error! data[%d] = %d, ref = %dn", i, data[i], x);
return false;
}
return true;
}
int main(int argc, char *argv[]) {
int devID;
cudaDeviceProp deviceProps;
printf("[%s] - Starting...n", argv[0]);
// This will pick the best possible CUDA capable device
devID = findCudaDevice(argc, (const char **)argv);
// get device name
checkCudaErrors(cudaGetDeviceProperties(&deviceProps, devID));
printf("CUDA device [%s]n", deviceProps.name);
int n = 16 * 1024 * 1024;
int nbytes = n * sizeof(int);
int value = 26;
// allocate host memory
int *a = 0;
checkCudaErrors(cudaMallocHost((void **)&a, nbytes));
memset(a, 0, nbytes);
// allocate device memory
int *d_a = 0;
checkCudaErrors(cudaMalloc((void **)&d_a, nbytes));
checkCudaErrors(cudaMemset(d_a, 255, nbytes));
// set kernel launch configuration
dim3 threads = dim3(512, 1);
dim3 blocks = dim3(n / threads.x, 1);
// create cuda event handles
cudaEvent_t start, stop;
checkCudaErrors(cudaEventCreate(&start));
checkCudaErrors(cudaEventCreate(&stop));
StopWatchInterface *timer = NULL;
sdkCreateTimer(&timer);
sdkResetTimer(&timer);
checkCudaErrors(cudaDeviceSynchronize());
float gpu_time = 0.0f;
// asynchronously issue work to the GPU (all to stream 0)
checkCudaErrors(cudaProfilerStart());
sdkStartTimer(&timer);
cudaEventRecord(start, 0);
cudaMemcpyAsync(d_a, a, nbytes, cudaMemcpyHostToDevice, 0);
increment_kernel<<<blocks, threads, 0, 0>>>(d_a, value);
cudaMemcpyAsync(a, d_a, nbytes, cudaMemcpyDeviceToHost, 0);
cudaEventRecord(stop, 0);
sdkStopTimer(&timer);
checkCudaErrors(cudaProfilerStop());
// have CPU do some work while waiting for stage 1 to finish
unsigned long int counter = 0;
while (cudaEventQuery(stop) == cudaErrorNotReady) {
counter++;
}
checkCudaErrors(cudaEventElapsedTime(&gpu_time, start, stop));
// print the cpu and gpu times
printf("time spent executing by the GPU: %.2fn", gpu_time);
printf("time spent by CPU in CUDA calls: %.2fn", sdkGetTimerValue(&timer));
printf("CPU executed %lu iterations while waiting for GPU to finishn",
counter);
// check the output for correctness
bool bFinalResults = correct_output(a, n, value);
// release resources
checkCudaErrors(cudaEventDestroy(start));
checkCudaErrors(cudaEventDestroy(stop));
checkCudaErrors(cudaFreeHost(a));
checkCudaErrors(cudaFree(d_a));
exit(bFinalResults ? EXIT_SUCCESS : EXIT_FAILURE);
}
attrezzaturainizializzazione:La funzione findCudaDevice viene utilizzata per selezionare il miglior dispositivo CUDA e restituire l'ID del dispositivo.
devID = findCudaDevice(argc, (const char **)argv);
Ottieni le proprietà del dispositivo: la funzione cudaGetDeviceProperties ottiene le proprietà del dispositivo specificato, che includono il nome del dispositivo e altre informazioni.
checkCudaErrors(cudaGetDeviceProperties(&deviceProps, devID));
Allocazione della memoria: utilizzare cudaMallocHost per allocare memoria bloccata dalla pagina accessibile sulla CPU e cudaMalloc per allocare memoria sul dispositivo.
int *a = 0;
checkCudaErrors(cudaMallocHost((void **)&a, nbytes));
Imposta il blocco di thread e la griglia: qui la dimensione del blocco di thread è impostata su 512 thread e la dimensione della griglia viene calcolata dinamicamente in base alla dimensione dei dati.
dim3 threads = dim3(512, 1);
dim3 blocks = dim3(n / threads.x, 1);
Creare eventi e timer CUDA: gli eventi CUDA vengono utilizzati per registrare il tempo e i timer vengono utilizzati per misurare il tempo di esecuzione della CPU.
cudaEvent_t start, stop;
checkCudaErrors(cudaEventCreate(&start));
checkCudaErrors(cudaEventCreate(&stop));
Elaborazione del flusso CUDA: utilizzo di cudaMemcpyAsync per la copia della memoria asincrona, <<<blocks, threads> >>La sintassi avvia la funzione del kernel CUDA eseguita contemporaneamente incrementa_kernel.
cudaMemcpyAsync(d_a, a, nbytes, cudaMemcpyHostToDevice, 0);
increment_kernel<<<blocks, threads, 0, 0>>>(d_a, value);
cudaMemcpyAsync(a, d_a, nbytes, cudaMemcpyDeviceToHost, 0);
Tempistiche e attese: cudaEventRecord registra gli eventi e viene utilizzato per calcolare il tempo di esecuzione della GPU. Attendi il completamento dell'operazione GPU tramite cudaEventQuery(stop).
cudaEventRecord(start, 0);
// ...
cudaEventRecord(stop, 0);
Verifica dei risultati: utilizzare la funzione corrette_output per verificare la correttezza dei risultati del calcolo della GPU.
bool bFinalResults = correct_output(a, n, value);
Rilascio risorse: rilascia la memoria allocata e gli eventi CUDA.
checkCudaErrors(cudaEventDestroy(start));
checkCudaErrors(cudaEventDestroy(stop));
checkCudaErrors(cudaFreeHost(a));
checkCudaErrors(cudaFree(d_a));
Funzione kernel CUDA incrementa_kernel:
Questa semplice funzione del kernel CUDA viene utilizzata per incrementare ciascun elemento in un array di un valore specificato inc_value. blockIdx.x e threadIdx.x vengono utilizzati per calcolare l'indice globale idx di ciascun thread e quindi eseguire l'operazione di addizione.
__global__ void increment_kernel(int *g_data, int inc_value) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
g_data[idx] = g_data[idx] + inc_value;
}
Altre funzioni ausiliarie
checkCudaErrors:Controlla CUDASe è presente un errore nella chiamata della funzione.
sdkCreateTimer e sdkResetTimer: utilizzati per creare e reimpostare i timer.
sdkStartTimer e sdkStopTimer: utilizzati per avviare e arrestare i timer e registrare il tempo di esecuzione della CPU.