performance of large number calculations in python (python 2.7.3 and .net 4.0) -


there lot of general questions python performance in comparison other languages. i've got more specific example: there 2 simple functions wrote in python c#, both checking if int number prime.

python:

import time  def is_prime(n):     num =n/2     while num >1:         if n % num ==0:             return 0         num-=1     return 1  start = time.clock() probably_prime = is_prime(2147483629) elapsed = (time.clock() - start) print 'time : '+str(elapsed) 

and c#:

 using system.diagnostics;   public static bool isprime(int n)         {             int num = n/2;             while(num >1)             {                 if(n%num ==0)                 {                     return false;                 }                 num-=1;             }             return true;         }  stopwatch sw = new stopwatch();  sw.start();  bool result = functions.isprime(2147483629);  sw.stop();  console.writeline("time: {0}", sw.elapsed); 

and times ( surprise me begginer in python:)):

python: 121s; c#: 6s

could explain big diffrence come ?

without type information, python spends lot more time looking rather doing in big while loop.

you can run faster python syntax in couple of ways:

1) use pypy --- watches how code being run, notices types, , replaces slow-lookups fast machine code on fly --- it's pretty cool

2) use numba --- works standard cpython run-time , can used favorite python extension. adding decorator pre-compile function machine-code when gets called "typed" things (like integers).

i couldn't pypy timings, on system python code took 180s , numba-code took 14s.

here numba-code:

import numba @numba.jit(numba.bool_(numba.int64), nopython=true) def is_prime(n):     num =n/2     while num >1:        if n % num ==0:             return 0         num-=1     return 1 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -