【 在 feng321 的大作中提到: 】
: python可以直接计算大整数乘积,上万位都没问题。我好奇你的代码是如何利用Gpu算的?
这个很简单, 首先,需要一块计算显卡,一般用Nvidia的容易些, 安装好专用驱动和CUDA库,
python端, 选择一种支持显卡计算的python库, 比如numba, 或者cupy之类的
一般安装tenorflow或者pytorch做深度学习计算也都会需要这些步骤。
这里用的numba的cuda
一个生成素数的程序,从1000开始,搜索24000个整数:
from numba import cuda
import numpy as np
import math
from time import time
@cuda.jit
def gpu_prime_gen(a, b, result, n):
idx = cuda.threadIdx.x + cuda.blockDim.x * cuda.blockIdx.x
if idx < n :
if(b[idx]%2==0):
result[idx] = 0
else:
result[idx] = 3
while(result[idx]*result[idx] <= a[idx]):
if((b[idx] % result[idx]) == 0):
result[idx] = 0
break
else:
result[idx] += 2
else:
result[idx] = b[idx]
def main():
n = 8000
x = np.arange(1000,1000+n*3).astype(np.int32)
y = x+1
start = time()
x_device = cuda.to_device(x)
y_device = cuda.to_device(y)
out_device = cuda.device_array(n*3)
threads_per_block = 1024
blocks_per_grid = math.ceil(n*3 / threads_per_block)
# 使用默认流
gpu_prime_gen[blocks_per_grid, threads_per_block](x_device, y_device, out_device, n*3)
gpu_result = out_device.copy_to_host()
cuda.synchronize()
gpu_result = gpu_result[gpu_result>0]
print("gpu vector gpu_prime_gen time " + str(time() - start)+" got prime "+ str(len(gpu_result)))
print(gpu_result[:1024].astype(np.int32))
if __name__ == "__main__":
main()
--
修改:poggy FROM 124.126.0.*
FROM 124.126.0.*