我在我的带有 9600M GT gpu 的 macbook pro 上运行一个小型 C++/thrust 程序(如下),并且有兴趣了解函数 h 花费的时间,因为目标是尽可能快地运行此代码以获得更大的NEPS 值。
为此,我在函数中添加了 clock() 调用。
打印的时间表明几乎所有时间都花在了thrust::reduce 上。事实上,thrust::reduce 报告的时间是thrust::transform 的数百倍,它调用三个对每个元素的余弦调用。为什么?
当然,我对测量的时间持怀疑态度。我插入了第二次调用thrust::reduce 只是为了看看报告的时间是否相似:它不是。第二次调用报告的时间具有更高的差异并且更小。更多困惑:为什么?
我还尝试使用thrust::transform_reduce(已注释掉)来代替期望运行得更快的两个内核调用——相反,它慢了4%。为什么?
建议赞赏!
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sequence.h>
#include <iostream>
#include <stdio.h>
#include <stdint.h>
float NEPS = 6.0;
__device__ float EPS;
__device__ float SQEPS;
__device__ float CNV_win;
__device__ float CNV_dt;
int CNV_n;
float EU_dt;
__host__ __device__ float f(float x,float t){
return x*cos(t)+x*cos(t/SQEPS)+cos(t/EPS);
}
struct h_functor
{
const float x, t;
h_functor(float _x, float _t) : x(_x),t(_t) {}
__host__ __device__
float operator()(const float & t_f) const {
return f(x, t-CNV_win+CNV_dt*(t_f+1) )*CNV_dt;
}
};
clock_t my_clock() __attribute__ ((noinline));
clock_t my_clock() {
return clock();
}
float h(float x,float t){
float sum;
sum = CNV_dt*(f(x,t-CNV_win/2)+f(x,t+CNV_win/2))/2;
clock_t start = my_clock(), diff1, diff2, diff3, diff4, diff5;
thrust::device_vector<float> t_f(CNV_n-2);
diff1 = my_clock() - start;
/* initialize t_f to 0.. CNV_n-3 */
start = my_clock();
thrust::sequence(t_f.begin(), t_f.end());
diff2 = my_clock() - start;
start = my_clock();
thrust::transform(t_f.begin(), t_f.end(), t_f.begin(), h_functor(x,t));
diff3 = my_clock() - start;
start = my_clock();
sum += thrust::reduce(t_f.begin(), t_f.end());
diff4 = my_clock() - start;
start = my_clock();
sum += thrust::reduce(t_f.begin(), t_f.end());
diff5 = my_clock() - start;
#define usec(d) (d)
fprintf(stderr, "Time taken %ld %ld %ld %ld %ld usecs\n", usec(diff1), usec(diff2), usec(diff3), usec(diff4), usec(diff5));
/* a bit slower, surprisingly:
sum += thrust::transform_reduce(t_f.begin(), t_f.end(), h_functor(x,t), 0, thrust::plus<float>());
*/
return sum;
}
main(int argc, char ** argv) {
if (argc >= 1) NEPS = strtod(argv[1], 0);
fprintf(stderr, "NEPS = %g\n", NEPS);
EPS= powf(10.0,-NEPS);
SQEPS= powf(10.0,-NEPS/2.0);
CNV_win= powf(EPS,1.0/4.0);
CNV_dt = EPS;
CNV_n = powf(EPS,-3.0/4.0);
EU_dt = powf(EPS,3.0/4.0);
cudaMemcpyToSymbol(CNV_win, &CNV_win, sizeof(float));
cudaMemcpyToSymbol(CNV_dt, &CNV_dt, sizeof(float));
cudaMemcpyToSymbol(SQEPS, &SQEPS, sizeof(float));
cudaMemcpyToSymbol(EPS, &EPS, sizeof(float));
float x=1.0;
float t = 0.0;
int n = floor(1.0/EU_dt);
fprintf(stderr, "CNV_n = %d\n", CNV_n);
while (n--) {
float sum = h(x,t);
x=x+EU_dt*sum;
t=t+EU_dt;
}
printf("%f\n",x);
}