Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I was working with Cython, while I was watching out for methods to optimize Python code. Cython is something that takes my attention the most; instead of printing C-code for yourself, you can choose to have other data types in your python code itself.

Here is a test I attempted,

#!/usr/bin/python

# test.pyx

def test(value):

    for i in xrange(value):

    i**2

    if(i==1000000):

        print i

test(10000001)

$ time python test.pyx

real    0m16.774s 

user    0m16.745s

sys     0m0.024s

$ time cython test.pyx

real    0m0.513s 

user    0m0.196s 

sys     0m0.052s

1 Answer

0 votes
by (108k points)

When I was executing the code you have done with distutils, I got very negligible peed gains over pure Python – about 1%. But, when I attached a few small changes to your code:

def test(long long value):

    cdef long long I 

    cdef long long z

    for i in xrange(value):

        z = i**2

        if(i==1000000):

            print i

        if z < i:

            print "yes"

and compiled it, I got the following times:

Pure Python code: 20.4553578737 seconds

Cython code: 0.199339860234 seconds

That’s a 100× speed-up. 

Want to become a Python Developer? Check out this insightful Python Certification course.

Browse Categories

...