编辑:感谢您之前的答案.但事实上我想在CUDA中做到这一点,显然CUDA没有功能填充.我必须为每个线程填充一次矩阵,所以我想确保我使用最快的方式.这个for循环是我最好的选择吗?
我想将float的矩阵设置为可能的最大值(在float中).做这份工作的正确方法是什么?
float *matrix=new float[N*N];
for (int i=0;i<N*N;i++){
matrix[i*N+j]=999999;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
har*_*ism 18
CUDA中最简单的方法是使用thrust :: fill.CUDA 4.0及更高版本中包含了Thrust ,如果您使用的是CUDA 3.2 ,则可以安装它.
#include <thrust/fill.h>
#include <thrust/device_vector.h>
...
thrust::device_vector<float> v(N*N);
thrust::fill(v.begin(), v.end(), std::numeric_limits<float>::max()); // or 999999.f if you prefer
Run Code Online (Sandbox Code Playgroud)
你也可以写这样的纯CUDA代码:
template <typename T>
__global__ void initMatrix(T *matrix, int width, int height, T val) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
for (int i = idx; i < width * height; i += gridDim.x * blockDim.x) {
matrix[i]=val;
}
}
int main(void) {
float *matrix = 0;
cudaMalloc((void*)&matrix, N*N * sizeof(float));
int blockSize = 256;
int numBlocks = (N*N + blockSize - 1) / (N*N);
initMatrix<<<numBlocks, blockSize>>>(matrix, N, N,
std::numeric_limits<float>::max()); // or 999999.f if you prefer
}
Run Code Online (Sandbox Code Playgroud)
使用std::numeric_limits<float>::max()
和std::fill
作为:
#include <limits> //for std::numeric_limits<>
#include <algorithm> //for std::fill
std::fill(matrix, matrix + N*N, std::numeric_limits<float>::max());
Run Code Online (Sandbox Code Playgroud)
或者,std::fill_n
如(看起来更好):
std::fill_n(matrix, N*N, std::numeric_limits<float>::max());
Run Code Online (Sandbox Code Playgroud)
请参阅这些在线文档:
归档时间: |
|
查看次数: |
6267 次 |
最近记录: |