pycuda 在SourceModule代码段中使用printf

2 篇文章 0 订阅
2 篇文章 0 订阅

当初想调个代码,没有printf打印,可是难过了半天,最后还是同事翻了墙才找到了答案。

结果超级超级简单,添加#include <stdio.h>

详见样例:

import pycuda.driver as cuda
import pycuda.autoinit
from pycuda.compiler import SourceModule
mod = SourceModule("""
    #include <stdio.h>
    __global__ void say_hi()
    {
      printf("I am %d.%d\\n", threadIdx.x, threadIdx.y);
    }
    """)
func = mod.get_function("say_hi")

func(block=(4,4,1))


是不是不太相信,来吧,官网demo   UsingPrintf   

啦啦啦啦

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
使用PyCUDA可以利用GPU加速这个求解拉普拉斯方程的过程。以下是使用PyCUDA优化的代码: ```python import numpy as np import pycuda.autoinit import pycuda.driver as drv from pycuda.compiler import SourceModule import matplotlib.pyplot as plt # Set maximum iteration maxIter = 500 # Set Dimension and delta lenX = lenY = 20 delta = 1 # Boundary condition Ttop = 100 Tbottom = 0 Tleft = 0 Tright = 0 # Initial guess of interior grid Tguess = 30 # Set meshgrid X, Y = np.meshgrid(np.arange(0, lenX), np.arange(0, lenY)) # Set array size and set the interior value with Tguess T = np.empty((lenX, lenY), dtype=np.float32) T.fill(Tguess) # Set Boundary condition T[(lenY-1):, :] = Ttop T[:1, :] = Tbottom T[:, (lenX-1):] = Tright T[:, :1] = Tleft # Define the CUDA kernel for updating the temperature values mod = SourceModule(""" __global__ void update_T(float *T, int lenX, int lenY) { int i = blockDim.x * blockIdx.x + threadIdx.x + 1; int j = blockDim.y * blockIdx.y + threadIdx.y + 1; if (i < lenX-1 && j < lenY-1) { T[i*lenY+j] = 0.25 * (T[(i+1)*lenY+j] + T[(i-1)*lenY+j] + T[i*lenY+j+1] + T[i*lenY+j-1]); } } """) # Get the kernel function update_T = mod.get_function("update_T") # Set the grid and block sizes block_size = (16, 16, 1) grid_size = ((lenX-2)//block_size[0]+1, (lenY-2)//block_size[1]+1, 1) # Iteration (We assume that the iteration is convergence in maxIter = 500) print("Please wait for a moment") for iteration in range(0, maxIter): update_T(drv.InOut(T), np.int32(lenX), np.int32(lenY), block=block_size, grid=grid_size) print("Iteration finished") # Configure the contour plt.title("Contour of Temperature") plt.contourf(X, Y, T, 50, cmap=plt.cm.jet) # Set Colorbar plt.colorbar() # Show the result in the plot window plt.show() ``` 这个代码与原始代码非常相似,但是使用PyCUDA的GPU并行计算来加速迭代计算的过程。在这个例子,我们定义了一个CUDA内核函数来更新温度值,并使用PyCUDA的函数调用语法将数组传递到GPU上进行计算。在每次迭代,我们使用PyCUDA函数调用来更新温度数组的值。最后,我们使用matplotlib库创建温度的轮廓图。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值