【发布时间】:2013-12-16 21:23:13
【问题描述】:
为了研究,我们必须分析 CPU 和 GPU 之间的性能差异。我的问题是我有一个只有 cpp 代码的 .cu 文件和一个具有完全相同代码的 .cpp 文件。但存在性能差异,即 .cu 文件的运行速度比 .cpp 文件快 3 倍。 .cu 文件会被 NVCC 编译器编译,但是 NVCC 编译器只会编译 cuda 代码,没有 cuda 代码,所以它会被宿主 cpp 编译器编译。这就是我的问题。我不明白性能差异。
#include <iostream>
#include <conio.h>
#include <ctime>
#include <cuda.h>
#include <cuda_runtime.h> // Stops underlining of __global__
#include <device_launch_parameters.h> // Stops underlining of threadIdx etc.
using namespace std;
void FindClosestCPU(float3* points, int* indices, int count) {
// Base case, if there's 1 point don't do anything
if(count <= 1) return;
// Loop through every point
for(int curPoint = 0; curPoint < count; curPoint++) {
// This variable is nearest so far, set it to float.max
float distToClosest = 3.40282e38f;
// See how far it is from every other point
for(int i = 0; i < count; i++) {
// Don't check distance to itself
if(i == curPoint) continue;
float dist = sqrt((points[curPoint].x - points[i].x) *
(points[curPoint].x - points[i].x) +
(points[curPoint].y - points[i].y) *
(points[curPoint].y - points[i].y) +
(points[curPoint].z - points[i].z) *
(points[curPoint].z - points[i].z));
if(dist < distToClosest) {
distToClosest = dist;
indices[curPoint] = i;
}
}
}
}
int main()
{
// Number of points
const int count = 10000;
// Arrays of points
int *indexOfClosest = new int[count];
float3 *points = new float3[count];
// Create a list of random points
for(int i = 0; i < count; i++)
{
points[i].x = (float)((rand()%10000) - 5000);
points[i].y = (float)((rand()%10000) - 5000);
points[i].z = (float)((rand()%10000) - 5000);
}
// This variable is used to keep track of the fastest time so far
long fastest = 1000000;
// Run the algorithm 2 times
for(int q = 0; q < 2; q++)
{
long startTime = clock();
// Run the algorithm
FindClosestCPU(points, indexOfClosest, count);
long finishTime = clock();
cout<<"Run "<<q<<" took "<<(finishTime - startTime)<<" millis"<<endl;
// If that run was faster update the fastest time so far
if((finishTime - startTime) < fastest)
fastest = (finishTime - startTime);
}
// Print out the fastest time
cout<<"Fastest time: "<<fastest<<endl;
// Print the final results to screen
cout<<"Final results:"<<endl;
for(int i = 0; i < 10; i++)
cout<<i<<"."<<indexOfClosest[i]<<endl;
// Deallocate ram
delete[] indexOfClosest;
delete[] points;
_getch();
return 0;
}
这两个文件的唯一区别是,一个是.cu文件,会被NVCC编译,另一个是.cpp文件,会被cpp编译器正常编译。
【问题讨论】:
-
您在每种情况下使用的编译命令是什么?您系统上每种情况下的实际时间测量值是多少?
-
我用 Visual Studio 2012 编译它。.cu 版本需要 ~2000 毫秒,.cpp 版本需要 ~8000 毫秒。我总是用“开始而不调试”来启动程序。
-
好吧,这是我的错。我使用了调试配置而不是发布配置。当我在真实配置下尝试时,没有时差。
-
如果您还发现了使用调试配置运行时的问题,请编辑您的答案并发布原因。