c++ - 如何对 CUDA 程序进行基准测试?
问题描述
我试图对我的第一个 CUDA 应用程序进行基准测试,该应用程序首先使用 CPU 然后使用 GPU 添加两个数组。
这是程序。
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include<iostream>
#include<chrono>
using namespace std;
using namespace std::chrono;
// add two arrays
void add(int n, float *x, float *y) {
for (int i = 0; i < n; i++) {
y[i] += x[i];
}
}
__global__ void addParallel(int n, float *x, float *y) {
int i = threadIdx.x;
if (i < n)
y[i] += x[i];
}
void printElapseTime(std::chrono::microseconds elapsed_time) {
cout << "completed in " << elapsed_time.count() << " microseconds" << endl;
}
int main() {
// generate two arrays of million float values each
cout << "Generating two lists of a million float values ... ";
int n = 1 << 28;
float *x, *y;
cudaMallocManaged(&x, sizeof(float)*n);
cudaMallocManaged(&y, sizeof(float)*n);
// begin benchmark array generation
auto begin = high_resolution_clock::now();
for (int i = 0; i < n; i++) {
x[i] = 1.0f;
y[i] = 2.0f;
}
// end benchmark array generation
auto end = high_resolution_clock::now();
auto elapsed_time = duration_cast<microseconds>(end - begin);
printElapseTime(elapsed_time);
// begin benchmark addition cpu
begin = high_resolution_clock::now();
cout << "Adding both arrays using CPU ... ";
add(n, x, y);
// end benchmark addition cpu
end = high_resolution_clock::now();
elapsed_time = duration_cast<microseconds>(end - begin);
printElapseTime(elapsed_time);
// begin benchmark addition gpu
begin = high_resolution_clock::now();
cout << "Adding both arrays using GPU ... ";
addParallel << <1, 1024 >> > (n, x, y);
cudaDeviceSynchronize();
// end benchmark addition gpu
end = high_resolution_clock::now();
elapsed_time = duration_cast<microseconds>(end - begin);
printElapseTime(elapsed_time);
cudaFree(x);
cudaFree(y);
return 0;
}
但令人惊讶的是,该程序正在生成以下输出。
Generating two lists of a million float values ... completed in 13343211 microseconds
Adding both arrays using CPU ... completed in 543994 microseconds
Adding both arrays using GPU ... completed in 3030147 microseconds
我想知道我到底哪里错了。为什么 GPU 计算比在 CPU 上运行的计算时间长 6 倍。
供您参考,我在 Intel i7 8750H 和 Nvidia GTX 1060 上运行 Windows 10。
解决方案
请注意,您的统一内存阵列包含 2.68亿个浮点数,这意味着您在调用内核时将大约 1 GB 的数据传输到设备。使用 GPU 分析器(nvprof、nvvp 或 nsight),您应该会看到 HtoD 传输占用了大部分计算时间。
推荐阅读
- ios - 共享图像对象时 UIActivityViewController 不显示消息选项
- node.js - 如何使用 Redis 作为 Express Session NestJS 的存储
- multithreading - 在后台作业中使用特征对象(不同的线程)
- javascript - 使用三星键盘的 Android 10 操作系统与 HTML 表单上的电话#输入字段交互很奇怪
- python - 无法创建具有预设条件的新数据框
- c# - 为什么这个音频源不播放任何东西?
- python - 图像处理卷积:为什么我要从 np.arange(pad, imgWidth+pad) 中滑动我的内核?
- javascript - 获取单选按钮的值中的问题
- azure-machine-learning-studio - 在 Azure 机器学习设计器中的“JobProperties”类型的对象上找不到成员“intellectualPropertyPublisher”
- pine-script - Pinescript line.new 在图表上绘制两条线