【问题标题】:I get an error when I try to use printf() in a kernel当我尝试在内核中使用 printf() 时出现错误
【发布时间】:2013-01-27 19:25:22
【问题描述】:

我正在使用 Visual Studio 2010 和具有计算能力 2.0 的 GTX480。

我尝试将 sm 设置为 2.0,但是当我尝试在内核中使用 printf() 时,我得到:

错误:从 __device__/__global__ 调用主机函数(“printf”) 不允许使用函数(“测试”)

这是我的代码:

#include "util\cuPrintf.cu"
#include <cuda.h>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <cuda_runtime.h>

__global__ void test (void)
{
  printf("Hello, world from the device!\n");
}

void main(void)
{
    test<<<1,1>>>();
    getch();
}

我在这里找到一个例子:“CUDA_C_Programming_Guide”'page _106'“B.16.4 Examples” 最后,这对我有用:D 谢谢。

#include "stdio.h"
#include <conio.h>

// printf() is only supported
// for devices of compute capability 2.0 and higher

  #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 200)
      #define printf(f, ...) ((void)(f, __VA_ARGS__),0)
  #endif


__global__ void helloCUDA(float f)
{
    printf("Hello thread %d, f=%f\n", threadIdx.x, f);
}

int main()
{
    helloCUDA<<<1, 5>>>(1.2345f);
    cudaDeviceSynchronize();
    getch();
    return 0;
}

【问题讨论】:

  • 在内核调用后添加cudaDeviceSynchronize()。仅包括 iostreamcuda_runtime.h
  • @sgar91:内核 printf 需要 cstdio
  • @talonmies.. iostreamcstdio 的超集。我可以通过包含iostream 来使用printf
  • 由于英语不是您的第一语言,如果您将来使用拼写检查器将不胜感激。
  • 感谢您的建议

标签: cuda


【解决方案1】:

如果您收到该错误,则可能意味着您的 GPU 不具备 2.x 或更高版本的计算能力。 This thread 更详细地介绍了在内核函数中打印的选项。

【讨论】:

  • 问题中指定OP有Compute 2.0设备。
  • 啊,它在标题中,我略读了一下。对不起!
  • 我查了一下,GTX 480 计算能力是2.0 developer.nvidia.com/cuda-gpus
【解决方案2】:

您可能正在为不支持 printf() 的体系结构进行编译。默认情况下,该项目针对计算架构 1.0 进行编译。要更改此设置,请在 VS 中打开项目属性 -> CUDA C/C++ -> 设备并将“代码生成”属性更改为“compute_20,sm_20”。

您不需要#include "util\cuPrintf.cu"。请参阅this 了解有关如何使用 printf 以及如何刷新输出以便您实际看到结果的详细信息。

【讨论】:

  • 非常感谢,在 "CUDA_C_Programming_Guide" 'page _106' "B.16.4 Examples" 我找到了答案。 #if defined(CUDA_ARCH) && (CUDA_ARCH VA_ARGS),0) #endif
【解决方案3】:

要在内核代码中使用printf,你必须做三件事:

  1. 确保cstdiostdio.h 包含在内核编译单元中。 CUDA通过重载实现内核printf,所以你必须包含那个文件
  2. 为计算能力 2.x 或 3.x 编译您的代码并在受支持的 GPU 上运行它(因此将 -arch=sm_20 之类的内容传递给 nvcc 或 Visual Studio 或 Nsight Eclipse 版本中的 IDE 等效项)
  3. 通过在主机代码中包含显式或隐式同步点来确保内核已完成运行(例如cudaDeviceSynchronize)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 2021-03-17
  • 1970-01-01
  • 2020-09-03
相关资源
最近更新 更多