[python-uk] C is it faster than numpy

Giorgio Zoppi giorgio.zoppi at gmail.com
Fri Feb 25 04:41:50 EST 2022


Well,
numpy is written in C :) Maybe your C is not the numpy equivalent?
Best Regards,
Giorgio

Il giorno ven 25 feb 2022 alle ore 09:03 BELAHCENE Abdelkader <
abdelkader.belahcene at enst.dz> ha scritto:

> Hi,
> a lot of people think that C (or C++) is faster than python, yes I agree,
> but I think that's not the case with numpy, I believe numpy is faster than
> C, at least in some cases.
>
>
> *Is there another explanation ?Or where can find  a doc speaking  about
> the subject?*Thanks a lot
> Regards
> Numpy implements vectorization for arrays, or I'm wrong. Anyway here is an
> example Let's look at the following case:
> Here is the result on my laptop i3:
>
> Labs$ *python3 tempsExe.py  50000*
>   sum with Python: 1250025000 and NumPy 1250025000
>       time used Python Sum: * 37.28 sec *
>       time used  Numpy Sum:  *1.85 sec*
>
> Labs$ *./tt    50000 *
>
>
> *   CPU  time :7.521730    The value : 1250025000 *
> --------------------------------------------
>
> This is the Python3 program :
>
> import timeit as it
> import numpy as np
> import sys
> try :
> n=eval(sys.argv[1])
> except:
> print ("needs integer as argument") ; exit()
>
> a=range(1,n+1)
> b=np.array(a)
> def func1():     return sum(a)
> def func2(): return np.sum(b)
>
> print(f"sum with Python: {func1()} and NumPy {func2()} ")
> tm1=it.timeit(stmt=func1, number=n)
> print(f"time used Python Sum: {round(tm1,2)} sec")
> tm2=it.timeit(stmt=func2, number=n)
> print(f"time used  Numpy Sum: {round(tm2,2)} sec")
>
> and Here the C program:
> #include <time.h>
> #include <stdio.h>
> #include <stdlib.h>
> long func1(int n){
>          long  r=0;
>         for (int  i=1; i<= n;i++) r+= i;
>          return r;
> }
> int main(int argc, char* argv[]){
>          clock_t c0, c1;
>         long v,count; int n;
>        if ( argc < 2) {
>               printf("Please give an argument");
>              return -1;
>       }
>     n=atoi(argv[1]);
>     c0 = clock();
>      *for (int j=0;j < n;j++) v=func1(n);*
>      c1 = clock();
>      printf ("\tCPU  time :%.2f sec", (float)(c1 - c0)/CLOCKS_PER_SEC);
>      printf("\n\tThe value : %ld\n",  v);
> }
> _______________________________________________
> python-uk mailing list
> python-uk at python.org
> https://mail.python.org/mailman/listinfo/python-uk
>


-- 
Life is a chess game - Anonymous.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/python-uk/attachments/20220225/696f2e15/attachment.html>


More information about the python-uk mailing list