Published on

HelloCuda 系列: CUDA nsys Profiler

CUDA nsys Profiler 是 NVIDIA 提供的强大工具,用于分析和优化 CUDA 程序的性能。它可以帮助开发者识别性能瓶颈、内存使用情况以及 GPU 计算效率。

以下面的代码来进行实战练习一下 nsys 的基本用法。 (以下只是一个简单的实例,实际上这么小的数据没必要使用 GPU 来处理,主要是为了演示如何使用 nsys 进行性能分析。)

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sort.h>
#include <thrust/reduce.h>
#include <iostream>

void thrustBasic() {
   int host_data[] = {1, 2, 3, 4, 5};

   // Transfer data to device using Thrust
   thrust::device_vector<int> d_data(host_data, host_data + 5);

   // Sort data on the device
   thrust::sort(d_data.begin(), d_data.end());

   // Sum of the data on the device
   int sum = thrust::reduce(d_data.begin(), d_data.end(), 0, thrust::plus<int>());
   std::cout << "Sum of sorted data: " << sum << std::endl;

   // Transfer data back to host
   // o1:
   thrust::host_vector<int> h_data = d_data;
   
   // o2:
   // thrust::copy(d_data.begin(), d_data.end(), host_data);

   std::cout << "Sorted data: ";
   for (int i = 0; i < 5; ++i) {
      std::cout << host_data[i] << " ";
   }

   std::cout << std::endl;
}

int main() {
   thrustBasic();

    return 0;
}

编译和运行

nvcc -Wno-deprecated-gpu-targets -rdc=true hello_world.cu -arch=sm_61 -o hello_world && ./hello_world

使用 nsys 进行性能分析

nsys profile --stats=true ./hello_world

查看结果

nsys-ui /home/ztgx/Desktop/report2.nsys-rep

导出

nsys export --type=json /home/ztgx/Desktop/report2.nsys-rep -o output.csv

分析结果

在使用 nsys 进行性能分析后,可以查看生成的报告文件,了解 GPU 计算的各个方面,包括内核执行时间、内存传输时间等。通过这些数据,可以识别出性能瓶颈并进行相应的优化。

主要关注耗时的部分,内存传输和内核执行时间,最直接的方式就是把report丢给 AI, 让大模型来帮助分析性能。

THE END