SHARE
TWEET

mandelbrot_cuda

sleiphyr Jun 20th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2. from pylab import imshow, show
  3. from timeit import default_timer as timer
  4. from numba import cuda
  5.  
  6. def mandel(x, y, max_iters):
  7.   c = complex(x, y)
  8.   z = 0.0j
  9.   for i in range(max_iters):
  10.     z = z*z + c
  11.     if (z.real*z.real + z.imag*z.imag) >= 4:
  12.       return i
  13.  
  14.   return max_iters
  15.  
  16. def create_fractal(min_x, max_x, min_y, max_y, image, iters):
  17.   height = image.shape[0]
  18.   width = image.shape[1]
  19.  
  20.   pixel_size_x = (max_x - min_x) / width
  21.   pixel_size_y = (max_y - min_y) / height
  22.    
  23.   for x in range(width):
  24.     real = min_x + x * pixel_size_x
  25.     for y in range(height):
  26.       imag = min_y + y * pixel_size_y
  27.       color = mandel(real, imag, iters)
  28.       image[y, x] = color
  29.  
  30. mandel_gpu = cuda.jit(device=True)(mandel)
  31.  
  32. @cuda.jit
  33. def mandel_kernel(min_x, max_x, min_y, max_y, image, iters):
  34.   height = image.shape[0]
  35.   width = image.shape[1]
  36.  
  37.   pixel_size_x = (max_x - min_x) / width
  38.   pixel_size_y = (max_y - min_y) / height
  39.  
  40.   startX, startY = cuda.grid(2)
  41.   gridX = cuda.gridDim.x * cuda.blockDim.x
  42.   gridY = cuda.gridDim.y * cuda.blockDim.y
  43.  
  44.   for x in range(startX, width, gridX):
  45.     real = min_x + x * pixel_size_x
  46.     for y in range(startY, height, gridY):
  47.       imag = min_y + y * pixel_size_y
  48.       image[y, x] = mandel_gpu(real, imag, iters)
  49.  
  50. gimage = np.zeros((1024, 1536), dtype = np.uint8)
  51. blockdim = (32, 8)
  52. griddim = (32,16)
  53.  
  54. start = timer()
  55. d_image = cuda.to_device(gimage)
  56. mandel_kernel[griddim, blockdim](-2.0, 1.0, -1.0, 1.0, d_image, 20)
  57. d_image.to_host()
  58. dt = timer() - start
  59.  
  60. print("Mandelbrot created on GPU in {} s".format(dt))
  61.  
  62. imshow(gimage)
  63. show()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top