C is it always faster than nump?

Chris Angelico rosuav at gmail.com
Fri Feb 25 14:47:00 EST 2022


On Sat, 26 Feb 2022 at 05:49, Richard Damon <Richard at damon-family.org> wrote:
>
> On 2/25/22 4:12 AM, BELAHCENE Abdelkader wrote:
> > 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.
> >
> My understanding is that numpy is written in C, so for it to be faster
> than C, you are saying that C is faster that C.

Fortran actually, but ultimately, they both get compiled to machine code.

Really, what the OP has demonstrated is that good, well-written code
called from bad code produces meaningless numbers that are not the
same as bad code written in C. I can't even use that to prove that
good code is faster than bad code, since the measurements aren't
comparable; but if that were what was being measured, it wouldn't be
very surprising.

To do a fair comparison of C and Numpy, you'd have to:

1) Use the same type of timer
2) Use the same algorithm (unless you're benchmarking "naive C code"
against "well-written Fortran code")
3) Have comparable levels of compile-time optimization
4) Cope with the vagaries of CPU caching
5) Ensure that the same data types are being used everywhere
6) Probably several other things that I didn't think of.

The precise way you run the test could easily skew it by orders of
magnitude in either direction.

> The key point is that numpy was written by skilled programmers who
> carefully optimized their code to be as fast as possible for the major
> cases. Thus it is quite possible for the numpy code to be faster in C
> than code written by a person without that level of care and effort.

This is clearly true.

ChrisA


More information about the Python-list mailing list