Using Cython, psyco and other tricks to make Python run faster

This is a good post showing how "perrygeo" uses Cython to speed up a pure Python function. The comments also discuss alternatives and options:

  • Using psyco instead of Cython
  • Using optimization flags for gcc
  • Using xxx instead of math.xxx

http://www.perrygeo.net/wordpress/?p=116

There are also the official Cython docs, and the Cython basic tutorial (hello world of cython)

xxx instead of math.xxx

I tried a simple benchmark of math.cos versus cos()

import math
from math import cos, pi
import time as t
 
ten_mill = 10000000
 
def do_mathcos():
	print 'do math.cos'
	x = math.pi
	i = ten_mill
	t0 = t.time()
	while(i):
		x = math.cos(x)
		i -= 1
	print t.time() - t0
 
def do_cos():
	print 'do cos'
	x = pi
	i = ten_mill
	t0 = t.time()
	while(i):
		x = cos(x)
		i -= 1
	print t.time() - t0
 
do_mathcos()
do_cos()
 
# OUTPUT:
# do math.cos
# 1.95301318169
# do cos
# 1.49543499947

So about 25% speedup, just by using:

from math import cos
# and calling cos()

Instead of:

import math
# and calling math.cos()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.