首页 > 解决方案 > 如何对 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。

标签: c++cudanvidia

解决方案


请注意,您的统一内存阵列包含 2.68亿个浮点数,这意味着您在调用内核时将大约 1 GB 的数据传输到设备。使用 GPU 分析器(nvprof、nvvp 或 nsight),您应该会看到 HtoD 传输占用了大部分计算时间。


推荐阅读