cuda使用thrust的api求一个向量的最值

懒得自己写了,就使用了thrust的api算了。还挺不错。

cuda程序
#include <thrust/extrema.h>
#include <thrust/device_ptr.h>
#include <iostream>


int main(){

  float* deviceArray;
  float max, test;
  int length = 1025;

  max = 0.0f;
  test = 2.5f;
  int size = (int) length*sizeof(float);

  cudaMalloc(&deviceArray, size);
  cudaMemset(deviceArray, 0.0f, size);
  cudaMemcpy(deviceArray, &test, sizeof(float),cudaMemcpyHostToDevice);

  thrust::device_ptr<float> d_ptr = thrust::device_pointer_cast(deviceArray);
  max = *(thrust::max_element(d_ptr, d_ptr + length));
  std::cout << max << std::endl;
}
求最值

具体变成代码就变成了下面的代码,但是加入caffe里面的时候会有编译错误。

template<typename Dtype>
Dtype get_device_array_max(Dtype * deviceArray,int length){
	thrust::device_ptr<Dtype> d_ptr = thrust::device_pointer_cast(deviceArray);
	Dtype max_value = *(thrust::max_element(d_ptr, d_ptr + length));
	return max_value;
}
template<typename Dtype>
Dtype get_device_array_min(Dtype * deviceArray,int length){
	thrust::device_ptr<Dtype> d_ptr = thrust::device_pointer_cast(deviceArray);
	Dtype min_value = *(thrust::min_element(d_ptr, d_ptr + length));
	return min_value;
}

可以把头文件

#include <thrust/extrema.h>
#include <thrust/device_ptr.h>

加到math_functions.hpp中问题解决,具体不知道什么原因。

posted @ 2018-04-26 14:52  开往春天的拖拉机  阅读(263)  评论(0编辑  收藏  举报