当您在设备内部调用cudaMalloc时,实际会发生什么
Whats actually happens when you call cudaMalloc inside device?
这实际上是有效的,所以我想知道cuda是否在线程中的设备上动态分配内存?如果是,__device__ malloc
有什么用,因为相比之下,它要快得多?我在问当你在内核中使用cudaMalloc时,幕后到底发生了什么,因为它看起来比堆上的设备malloc快得多。
#include <iostream>
#include <numeric>
#include <stdlib.h>
__global__ void testMem(int* time){
int* a;
cudaMalloc(&a,sizeof(int));
a[0] = 4;
time = a[0];
}
__global__ void testMem2(int* time){
}
int main(){
int* h_time = (int*)malloc(sizeof(int));
h_time[0] =0;
int* d_time;
cudaMalloc(&d_time,sizeof(int));
clock_t start1 = clock();
cudaMemcpy(d_time,h_time,sizeof(int),cudaMemcpyHostToDevice);
testMem<<<1,1>>>(d_time);
cudaMemcpy(h_time,d_time,sizeof(int),cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
clock_t end1 = clock();
int result = end1- start1;
//float result = (float)*h_time;
//result =result/ CLOCKS_PER_SEC;
std::cout<<result<<std::endl;
std::cout<<*h_time<<std::endl;
//std::cout<<(1<<10);
cudaFree(d_time);
free(h_time);
}
从计算能力3.5开始,您可以在内核中使用部分cuda运行时api。这些方法在文档中被声明为__host__ __device__
,就像这里一样:
__host__ __device__ cudaError_t cudaMalloc ( void** devPtr, size_t size )
在设备上分配内存。
执行此操作时,请提醒链接到设备运行库:cudadevrt.lib
。
还有另一种在设备上动态分配内存的方法:使用malloc
,这是以不同的方式实现的(本文对此进行了说明)。它使用的是一个小内存堆,不需要相同的计算能力。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- c++库的公共头文件中应该包含什么
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- ifstream什么都没读
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 我应该使用什么来代替void作为变体中的替代类型之一
- 当您在设备内部调用cudaMalloc时,实际会发生什么