Hướng dẫn can you make python as fast as c? - bạn có thể làm cho python nhanh như c?

Making Sense of Big Data

Faster Python Code With Numba

Photo by Charlotte Coneybeer on Unsplash

The Speed Issue

While it is widely accepted that Python, mostly due to its lean syntax, can act as a great prototyping language, it does come with a drawback that is commonly mentioned in “programming language war”-style debates: speed. Compared to other programming languages, Python’s run time for standard benchmark algorithms is much slower.

Created By Myself

Taking the fastest individual run times for several popular programming languages from the binary-tree benchmark on The Computer Language Benchmarks Game, Python’s 48.03 seconds stand no chance against 0.94 seconds in C++ or 1.54 seconds in C. Due to being an interpreted and dynamically typed language, Python allows for extremely fast prototyping speeds but is unable to compete with the run times of C++, C, Fortran, as well as several other compiled languages.

Fast Prototyping + Fast Run Times = Numba

Numba combines the best of the fast prototyping and fast run time worlds through a just-in-time (JIT) compiler for Python. All that really means is that your code will only be compiled at run time and not before. In doing so, Numba enables you to boost your Python code’s speed by “one to two orders of magnitude.”[2] The actual speed gains from using Numba, however, highly depend on each specific use case as the project focuses on scientific computing applications.

Installing Numba

One of Numba’s great advantages concerns its ease of use. As opposed to more or less complicated installation procedures required for alternative ways to speed up Python, Numba can be completely installed using pip or conda .

Both ways are extremely easy and should work out of the box with most data science environments. Using Anaconda, conda install numba will install all that is required. The same goes for pip install numba .

When To Use Numba

Once installed, Numba can help make Python code a lot faster. However, there are three main criteria that act as guidelines to determine how suitable Numba is for a specific task and, therefore, its potential to speed up Python.

  1. As mentioned above, Numba focuses on speeding up scientific applications. Thus, the more the code consists of mathematical operations, the more Numba is going to be able to help.
  2. Related to the first criteria, Numba works particularly well with NumPy. Chances are, Python code focusing on mathematical operations will contain plenty of NumPy. It is important to note, however, that Numba does not support all NumPy functions and some may have to be implemented in raw Python and supported NumPy functions in order to use them.
  3. The more loops, the better. Generally, Numba enables significant time savings when code contains several otherwise very lengthy loops.

Turning On The Turbo

Another reason for using Numba is the way in which it integrates with other Python code. The only requirement for using Numba is adding a decorator to the function that needs speeding up.

Code from Numba documentation

In the example above, the decorator @jit(nopython=True) signals to Numba to run in nopython mode as opposed to Numba’s alternative object mode. By default, the nopython argument is set to false even though it produces much faster code because of its resulting restrictions in the number of, for instance, NumPy functions that are supported. Alternatively to @jit(nopython=True) , one can also use the shorthand @njit.

Since the monte_carlo_pi function’s code ticks at least two of the three requirements that make a promising use case for Numba due to the for loop and focus on mathematical computation, adding the @njit decorator should provide a decent boost in performance.

Created By Myself

While the purely pythonic version of the function starts drastically slowing down at around 100 million samples passed to it, the equivalent Numba version retains a much higher level of performance with the relative gap between both options only widening with an increasing computational load.

More Decorating

Lazy compilation refers to letting Numba decide how to optimize the code. Generally, this option is fast to implement and minimizes the amount of errors that could potentially occur. The @jit decorator signals lazy compilation to Numba.

Created by Myself

In addition, lazy compilation will also allow you to retain a higher degree of flexibility. In essence, it can give Python functions a decent speed boost whilst still allowing for a high prototyping speed.

Eager compilation allows for more control regarding the function’s signature which could improve the code’s readability (and potentially performance). At the same time, specifying a signature also reduces the code’s flexibility and might lead to easily overlooked bugs. Signatures are added to the decorators above the function to be optimized. For instance, conda0 describes a function that takes an integer as input and returns an integer. Numba also allows for the specification of arrays in signatures through the following syntax: conda1 . The previously mentioned signature would specify an array of integers as input and an integer as output of a function.

Được tạo ra bởi chính tôi

Như được gợi ý trong phần giới thiệu về tổng hợp háo hức, tạo mẫu nhanh có thể dẫn đến các lỗi không bị phát hiện. Chữ ký của hàm conda2 mong đợi một loạt các số nguyên và sẽ trả về một số nguyên. Khi vượt qua mảng conda3, kết quả chính xác sẽ là conda4. Tuy nhiên, do chữ ký của chức năng, cuộc gọi chức năng ở trên sẽ trả về conda5 mà không cần ném ngoại lệ. Một chữ ký mang lại kết quả dự kiến ​​sẽ là, ví dụ, conda6. Do đó, bắt buộc phải xây dựng chính xác từng chữ ký của chức năng khi sử dụng tổng hợp háo hức với Numba.

Tuy nhiên, biến thể mạnh mẽ nhất của Numba từ JIT Decorator là @jit(nopython=True) hoặc tương đương @njit. Bằng cách kích hoạt chế độ Nopython, chức năng được đề cập sẽ không sử dụng bất kỳ API Python C C C và tạo mã nhanh hơn nhiều. Trái ngược với @jit, buộc Numba sử dụng chế độ Nopython sẽ ngăn chặn sự dự phòng đến chế độ đối tượng chậm hơn nhưng cũng đòi hỏi sự phát triển chuyên sâu hơn nhiều trong việc chuẩn bị trong khi cũng ít tha thứ hơn. Chạy ở chế độ đối tượng sẽ chịu đựng việc sử dụng các gói khoa học dữ liệu tiêu chuẩn khác như gấu trúc trong khi chế độ Nopython giành được.

Bản tóm tắt

Mặc dù khả năng của Numba, đi sâu hơn nhiều so với các phương pháp được mô tả trong bài viết này, nhưng việc nắm bắt tốt và hiểu cách làm việc với người trang trí @jit là một bước tiến lớn dường như không bao giờ kết thúc cho các vòng lặp và hướng tới thực hiện mã khoa học tốt hơn.

Khi nói đến việc tạo mẫu nhanh và thử nghiệm, Numba tích hợp hoàn hảo với Python thông qua quá trình cài đặt nhanh và dễ sử dụng. Thay vì phải cài đặt một trình biên dịch hoàn toàn mới hoặc trộn mã python với một ngôn ngữ khác, sử dụng numba cho phép các lập trình viên python chạy trên mặt đất chạy và tập trung vào mã của họ theo cách họ sẽ không tê liệt.

Được tạo ra bởi chính tôi

Tuy nhiên, Numba không phải là một kích thước phù hợp với tất cả các cách tiếp cận. Mọi trường hợp sử dụng tiềm năng nên được kiểm tra riêng biệt là tiết kiệm thời gian lớn hơn thông qua việc sử dụng chế độ Nopython đến với chi phí không thể sử dụng các gói khoa học dữ liệu tiêu chuẩn như gấu trúc. Do đó, như một nguyên tắc chung, hầu hết các ứng dụng có thể có lợi đủ từ việc để tê liệt tất cả các công việc tối ưu hóa thông qua công cụ trang trí @jit. Mặt khác, các trường hợp sử dụng nâng cao yêu cầu thời gian chạy thấp nhất có thể, mặt khác, đảm bảo các khoản đầu tư thời gian tiếp theo để làm cho chúng tương thích với Numba do hệ sinh thái phong phú và chức năng mở rộng mà dự án đi kèm.

Python có thể nhanh như C không?

Do là ngôn ngữ được diễn giải và gõ linh hoạt, Python cho phép tốc độ tạo mẫu cực kỳ nhanh nhưng không thể cạnh tranh với thời gian chạy của C ++, C, Fortran, cũng như một số ngôn ngữ được biên dịch khác.Python allows for extremely fast prototyping speeds but is unable to compete with the run times of C++, C, Fortran, as well as several other compiled languages.

Có thể làm cho Python nhanh không?

Sử dụng các chức năng tích hợp, nhiều chức năng tích hợp của Python được viết bằng C, giúp chúng nhanh hơn nhiều so với giải pháp Python thuần túy. Thực hiện một nhiệm vụ rất đơn giản là tổng hợp rất nhiều số. Chúng tôi có thể lặp qua từng số, tổng hợp khi chúng tôi đi. Many of Python's built-in functions are written in C, which makes them much faster than a pure python solution. Take a very simple task of summing a lot of numbers. We could loop through each number, summing as we go.

Chúng ta có thể làm cho Python nhanh như C ++ không?

Thực hiện Python sau khi sử dụng Numba.Vì vậy, Python nhanh hơn C ++.Vì vậy, có thể tăng tốc các thuật toán của bạn trong Python nhanh hơn C ++.Python is faster than C++. So it is possible to speed up your algorithms in Python to be faster than C++.

Python có chậm so với C không?

Mã Python bên trong được giải thích trong thời gian chạy thay vì được biên dịch thành mã gốc do đó nó chậm hơn một chút.Chạy tập lệnh Python V/S chạy mã C/C ++: Python: Đầu tiên nó được biên dịch thành mã byte.Mã byte này sau đó được giải thích và thực thi bởi PVM (máy ảo Python).it is a bit slower. Running of Python script v/s running of C/C++ code: Python: First it is compiled into Byte Code. This Byte Code is then interpreted and executed by the PVM (Python Virtual Machine).