温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

CUDA计时器怎么实现

发布时间:2021-12-30 14:06:08 来源:亿速云 阅读:106 作者:iii 栏目:互联网科技

本篇内容介绍了“CUDA计时器怎么实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

在进行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个数的平方

#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;
}

运行结果:

CUDA计时器怎么实现

“CUDA计时器怎么实现”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI