Home  >  Article  >  Backend Development  >  How to speed up Python programs

How to speed up Python programs

(*-*)浩
(*-*)浩Original
2019-07-05 14:29:322489browse

This time I will talk about a simple way to speed up python calculations, which is to use the numba library. The numba library can be compiled on-the-fly using JIT technology to achieve high performance. In addition, the computing power of cuda GPU can also be used. Acceleration is a very good tool library for speeding up Python. It is simple to use, but the installation is slightly more complicated.

How to speed up Python programs

#numba can be used after the installation is completed. (Recommended learning: Python video tutorial)

Write a small case below to see the difference between the accelerated program and the pre-accelerated program, borrowing the most classic example from the official website:

#!/usr/bin/env python
# coding=utf-8
from numba import jit
from numpy import arange
import time

@jit
def sum2d(arr):
    M, N = arr.shape
    result = 0.0
    for i in range(M):
        for j in range(N):
            result += arr[i,j]
    return result

a = arange(9).reshape(3,3)
start_time = time.time()
for i in range(10000000):
    sum2d(a)
end_time = time.time()
print (end_time - start_time)

Here we use numpy to generate a matrix with three rows and three columns, [[0,1,2],[3,4,5],[6,7,8]] and then do two-dimensional accumulation calculation , the value should obviously be 36. We have done 10000000 such calculations here. Using @jit annotation, we can directly use numba jit technology to compile in real time, thus improving the speed. The final running time is about 3.86s. If the annotation is removed, the running time is about It is 25.45s. It can be seen from here that there is about a 6.6 times performance improvement, so it is indeed convenient and simple to use numba to accelerate python programs.

For more Python related technical articles, please visit the Python Tutorial column Get studying!

The above is the detailed content of How to speed up Python programs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn