Tips for speeding up python code correctly with numba

This article is the 18th day article of MicroAd Advent Calendar 2020.

Introduction

numba is a library for speeding up python code.

Simply annotate the function you want to speed up as follows, and you will be able to execute it at the speed of native machine code.

import numba

@numba.jit
def f(x, y):
    return x + y

You can easily speed up the code by using numba, but it will compile unlike normal python code. If you use it without understanding the mechanism, the execution speed of the entire process may slow down.

In this article, I'll show you some surprising numba pitfalls and how to avoid them.

no use python mode

There are two modes in numba: __no python __ where optimization is performed and __object __ which is the same compilation method as usual.

The default setting is to switch between these two modes automatically. no python mode takes precedence, but if this fails it will automatically switch to object mode.

In addition to not being optimized in object mode The execution time may take longer due to the compilation overhead.

So, in order to utilize numba, understand the processing that does not support optimization, It is important to devise a function such as cutting out a function so that such processing is not included.

no python mode non-compliant processing
・ Dict
・ Set
・ Pandas
・ Yield from
・ Set ・ dict ・ Generator comprehension

Also, in numba, you can set an error if you can not compile in no python mode, so Basically, it is recommended to use the following writing style.

@jit(nopython=True)
def f(x, y):

or

@njit
def f(x, y):

Avoid compilation overhead

In numba, the timing to compile the function is automatically switched according to the implementation.

If you use it without knowing it, compilation will run in situations where processing speed is required, and The numba used for speeding up may return and become a bottleneck.

Since you are consciously manipulating the compile timing, let's understand its variations and how to write it.

Compile when the function is called for the first time

This is the default behavior.

@njit
def f(x, y):
  return x + y 

Compile when the function is loaded

By specifying the type, the function will be compiled at the defined timing. This writing method is the most recommended because the type specification also has the effect of speeding up.

@njit(int32(int32, int32))
def f(x, y):
    return x + y

Use cache

Also, by setting to use cache, you can do without compiling except for the first startup. This method can be used with other type specifications, so there is no loss even if you add options for the time being.

@njit(cache=True)
def f(x, y):
  return x + y

Ahead of compile

You can also prevent compilation from happening at run time by automatically creating a compiled module. To be honest, this method is a bit cumbersome and makes the code verbose. It's a last resort when you don't want to incur compilation overhead at any time.

from numba.pycc import CC

cc = CC('my_module')

@cc.export('multi', 'i4(i4, i4)')
def f(a, b):
    return a + b

if __name__ == "__main__":
    cc.compile()
>>> from my_module import f
>>> f(3, 4)

Summary

How was that. This time, you can easily achieve high speed, but I have summarized the points to note about numba, which has a slight quirk in operation. We hope that this article will be helpful to everyone who has read it.

Recommended Posts

Tips for speeding up python code correctly with numba
A note on speeding up Python code with Numba
I tried speeding up Python code including if statements with Numba and Cython
Roughly speed up Python with numba
Tips for dealing with binaries in Python
Tips for using python + caffe with TSUBAME
A collection of tips for speeding up learning and reasoning with PyTorch
~ Tips for Python beginners from Pythonista with love ① ~
~ Tips for Python beginners from Pythonista with love ② ~
Specific sample code for working with SQLite3 in Python
VS Code settings for developing in Python with completion
Reading, displaying and speeding up gifs with python [OpenCV]
Get country code with python
Set Up for Mac (Python)
Python code memo for yourself
Debug Python with VS Code
[Tips] Handle Athena with Python
[Python] Sample code for Python grammar
[Python + Selenium] Tips for scraping
~ Tips for beginners to Python ③ ~
Regarding speeding up python (memo)
Document Python code with Doxygen
Set up a Python development environment with Visual Studio Code
Tips for developing apps with Azure Cosmos DB in Python
[Python] Create a screen for HTTP status code 403/404/500 with Django
Mechanism for automatic lint check with flake8 when committing python code
Numba to speed up as Python
Tips for running Go with docker
Getting Started with Python for PHPer-Classes
[TouchDesigner] Tips for for statements using python
Tips for calling Python from C
Getting Started with Python for PHPer-Functions
[VS Code] ~ Tips when using python ~
Install python with mac vs code
Prepare a Python virtual environment for your project with venv with VS Code
About Python code for simple moving average assuming the use of Numba
Tips for Python beginners to use the Scikit-image example for themselves 6 Improve Python code
Easy keyword extraction with TermExtract for Python
INSERT into MySQL with Python [For beginners]
WEB scraping with Python (for personal notes)
[Python] Speeding up processing using cache tools
Manually ssh registration for coreserver with python
Use DeepL with python (for dissertation translation)
Memo to ask for KPI with python
Amplify images for machine learning with python
[Python] Round up with just the operator
[Shakyo] Encounter with Python for machine learning
Process multiple lists with for in Python
Tips for plotting multiple lines with pandas
Getting Started with Python for PHPer-Super Basics
python> coding guide> PEP 0008 --Style Guide for Python Code
I installed and used Numba with Python3.5
Debug for mysql connection with python mysql.connector
A tool for easily entering Python code
[Python] Read images with OpenCV (for beginners)
WebApi creation with Python (CRUD creation) For beginners
Speeding up numerical calculations with NumPy: Basics
Tips for making small tools in python
Preparation for scraping with python [Chocolate flavor]
[For beginners] Try web scraping with Python
R code compatible sheet for Python users