[Theory] How to speed up python code execution / pypy vs GPU

BartC bc at freeuk.com
Wed Nov 9 08:03:16 EST 2016


On 05/11/2016 17:10, Mr. Wrobel wrote:

> 1. What I have found is modified python interpreter - pypy  -
> http://pypy.org that does not require any different approach to develop
> your code.
>
> 2. And: Gpu based computing powered by Nvidia (NumbaPro compiler):
> https://developer.nvidia.com/how-to-cuda-python

Nice Mandelbrot benchmark link in that article. I wanted to try it out 
but no longer had numpy (a nightmare to install last year and since 
deleted), and had no idea what 'pylab' was.

I used the code below in pure Python (but Py3 because of the print 
functions). ('mandel_nc()' also dispenses with complex numbers - if you 
want to port elsewhere without complex support, or just understand what 
is being calculated.)

(Most of the runtime here seems to be spent in the print functions in 
writepgm().)

-----------------------------------------

#Mandelbrot test derived from:
# http://nbviewer.jupyter.org/gist/harrism/f5707335f40af9463c43

def mandel(x, y, max_iters):
   c = complex(x, y)
   z = 0.0j
   for i in range(max_iters):
     z = z*z + c
     if (z.real*z.real + z.imag*z.imag) >= 4:
       return i

   return max_iters

#def mandel_nc(x, y, max_iters):
#	a = b = 0
#	for i in range(max_iters):
#		a, b = a*a-b*b+x, 2*a*b+y
#		if (a*a + b*b) >= 4:
#			return i
#	return max_iters

def create_fractal(min_x, max_x, min_y, max_y, image, iters):
   height = len(image)
   width = len(image[0])

   pixel_size_x = (max_x - min_x) / width
   pixel_size_y = (max_y - min_y) / height

   for x in range(width):
     real = min_x + x * pixel_size_x
     for y in range(height):
       imag = min_y + y * pixel_size_y
       color = mandel(real, imag, iters)
#      color = mandel_nc(real, imag, iters)
       image[y][x] = color

def createimage(height,width):
	image = [[0 for i in range(width)] for i in range(height)]
	return image	

def writepgm(file,image,maxpixel=255):
	height = len(image)
	width=len(image[0])

	f = open(file, "w")
	print ("P2", file=f)
	print (width,height, file=f)
	print (maxpixel, file=f)

	for y in range(height):
		for x in range(width):
			print (image[y][x],"",end="",file=f)
		print (file=f)
	f.close()

maxpixel=20

im=createimage(1024,1536)
create_fractal(-2.0, 1.0, -1.0, 1.0, im, maxpixel)
writepgm("test.ppm",im,maxpixel)

-----------------------------------------

-- 
Bartc




More information about the Python-list mailing list