0

This is my fun.pyx file

cimport cython

@cython.boundscheck(False)
cdef long long int extr():
    cdef long long int i=0;
    while i<=20000000000:
        i=i+1
    return i

def fn():
    return extr()

This is my test.py file

from fun import fn
import time

t1=time.time()
print(fn())
print(time.time()-t1)

But after running this,I found only 3% increase in speed as compared with python program.How to optimize this program? Any suggestions would be helpfull. Thanks in advance.

SiHa
  • 7,830
  • 13
  • 34
  • 43
  • Did you mean to put 20,000,000,000? I don't know if Cython would promote a variable to a Python `int`, but if it does then it will need to use Python routines. – Ignacio Vazquez-Abrams Apr 11 '17 at 14:35
  • 2
    `def extr(): return 20000000001` should be pretty optimal. What real, non-toy thing are you trying to optimize, and how did you profile it? – Useless Apr 11 '17 at 14:36
  • @Useless I just want to optimize this loop.If you know please help.I was able to optimize using numba.But I want to do it with cython. –  Apr 11 '17 at 14:47
  • I told you how to optimize the loop: manual precomputation. No-one can possibly care about optimizing _this_ loop in any other way, because it doesn't do anything useful. It's almost never useful or instructive to optimize toy code that does nothing. It's almost never useful to try optimizing even real code until you've profiled it properly. – Useless Apr 11 '17 at 14:49
  • @Useless then how was numba able to optimize this code x100 faster? –  Apr 11 '17 at 14:51
  • Was it? If that's relevant information you care about, why isn't it in the question? If the real question is "Why is cython slower that some other thing I did," say what that thing is and ask _that_ question. – Useless Apr 11 '17 at 14:52
  • 1
    I don't think he was saying that information was useless, I think he was referencing your name. :) – Kade M. Apr 11 '17 at 14:55

1 Answers1

1

I ran the following benchmarks and found an appropriate speedup

cimport cython
from cython.operator cimport preincrement as inc
@cython.boundscheck(False)
cpdef long long int extr():
    cdef long long int i=0;
    while i<=200000:
        inc(i)
    return i

Python function

def pextr():
    i=0;
    while i<=200000:
        i +=1
    return i

Now benchmarking:

%timeit extr()


The slowest run took 16.55 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 67.2 ns per loop




%timeit pextr()


100 loops, best of 3: 15.6 ms per loop
In [3]:

Are you building this correctly? You will want to be using pyximport or have an appropriate setup.py script

I also notice you are using fn to execute this code, probably as you have realised it is impossible to import a cdef into a python file. However, if you just save your function as a cpdef, you can use it directly

user3684792
  • 2,542
  • 2
  • 18
  • 23