Get the App
SLTechnology News&Howtos  ›  Development  › 

Is Python faster than C++?

Shulou Source: shulou.com Published: 2022-06-01 13:03:31 10月01日 Update

This article introduces the knowledge of "is Python faster than C++". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

As we all know, Python is a dynamic language with global interpreter locks, which is slower than other static languages, and for this reason, you may want to turn to other languages such as Java, clocking, but wait a minute, share a technology that makes Python faster than C++ today, and then decide whether you want to turn it or not.

Today's protagonist is that Numba,Numba is an open source just-in-time compiler (JIT compiler) that converts Python and NumPy code into fast machine code to speed up performance. Can reach the speed of C or FORTRAN. Is it difficult to use it when it is so powerful? No,No,No,So easy, you don't need to replace the Python interpreter, you don't need to compile separately, you don't even need to install a C / C + compiler. Just put the decorator provided by Numba on top of the Python function, and leave the rest to Numba. Take a simple example:

From numba import jitimport random@jit (nopython=True) def monte_carlo_pi (nsamples): acc = 0 for i in range (nsamples): X = random.random () y = random.random () if (x * * 2 + y * * 2) < 1.0: acc + = 1 return 4.0 * acc / nsamples

Numba is designed for scientific computing, and when used with NumPy, Numba generates specialized code for different array data types to optimize performance:

Numba.jit (nopython=True, parallel=True) def logistic_regression (Y, X, w, iterations): for i in range (iterations): W-= np.dot (1.0 / (1.0 + np.exp (- Y * np.dot (X, w) * Y), X) return w

Now let's take a look at the performance comparison between the same code before and after using Numba and C++. For example, if we want to find all primes within 10 million, the algorithmic logic of the code is the same: Python code:

Import mathimport timedef is_prime (num): if num = = 2: return True if num

Tags: Code clocking running that is language loop compilation content functions parameters performance more knowledge compiler interpreter or speed interpretation different no Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi MySQL Linux macOS NVidia