[Python] Execution time when a function is entered in a dictionary value

Python without the switch (select) syntax may use a dictionary instead, A note about its execution time.

Conclusion

-** Insert the function itself : ** {key: func} ** - Short time ** --Only the function selected by the key is executed -** Enter the return value of the function **: ** {key: func ()} ** --It takes extra time --All functions are executed once and the return value is entered.

If the function arguments are different,

--Prepare (* args, ** kwargs) as the argument of the function in advance and absorb the difference. --The given argument itself is also a dictionary - e.g. dict_kwargs = { 1: { 'arg1': arg1 }, 2: { 'arg2': arg2 } }

The method is conceivable.

Example

Consider the case where the following two functions are executed separately. (I want to know the execution time, so I write it so that it will be slow.)

def myfunc1():
    nx, ny = 50, 40
    arr = np.empty( ( nx, ny ) )
    for iy in range( ny ):
        for ix in range( nx ):
            arr[ix,iy] = ix * ix + iy * iy
    return arr


def myfunc2():
    nx, ny = 50, 40
    arr = np.empty( ( nx, ny ) )
    for iy in range( ny ):
        for ix in range( nx ):
            arr[ix,iy] = 1
    return arr

After that, we measured the time required for the following three execution methods (using %% timeit of JupyterLab, below is myfunc1 only).

#Execute function directly
myfunc1()

# { key: func }Run from type dictionary
key = 1
dict_func = { 1: myfunc1, 2: myfunc2 }
dict_func[ key ]()

# { key: func() }Run from type dictionary
dict_return = { 1: myfunc1(), 2: myfunc2() }
dict_return[ key ]

The result was as follows. In the {key: func ()} type, you can see that it takes close to the time when both functions are executed.

#Direct execution
1: 488 µs ± 26.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2: 286 µs ± 925  ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# { key: func }Mold
1: 461 µs ± 332  ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2: 298 µs ± 22.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# { key: func() }Mold
1: 763 µs ± 3.96 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2: 771 µs ± 31.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Recommended Posts

[Python] Execution time when a function is entered in a dictionary value
Measure function execution time in Python
Precautions when pickling a function in python
Hash in Perl is a dictionary in Python
Function execution time (Python)
Create a dictionary in Python
[python] Manage functions in a dictionary (command table, function table, function pointer)
[Python] What is a zip function?
When writing a program in Python
When converting a string (a-> b) in Python, which is faster, if statement or dictionary type?
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
A function that measures the processing time of a method in python
[Python3] Define a decorator to measure the execution time of a function
A program that determines whether a number entered in Python is a prime number
What to do when the value type is ambiguous in Python?
In the python dictionary, if a non-existent key is accessed, initialize it with an arbitrary value
Notify using Notification Center when the execution environment is macOS in Python
A useful note when using Python for the first time in a while
What is the fastest way to create a reverse dictionary in python?
Draw a graph of a quadratic function in Python
To execute a Python enumerate function in JavaScript
Get the caller of a function in Python
A clever way to time processing in Python
Find the divisor of the value entered in python
Python Note: When assigning a value to a string
Isn't there a default value in the dictionary?
Output timing is incorrect when standard (error) output is converted to a file in Python
Check if the string is a number in python
This is a sample of function application in dataframe.
Get the value of a specific key in a list from the dictionary type in the list with Python
Receive dictionary data from a Python program in AppleScript
How to store Python function in Value of dictionary (dict) and call function according to Key
A memo when checking whether the specified key exists in the defined dictionary with python
How to unit test a function containing the current time using freezegun in python
Embedding in datetime when only the time is known
Things to note when initializing a list in Python
What's in that variable (when running a Python script)
Output python execution time
Time floor function (Python)
Use communicate () when receiving output in a Python subprocess
Creating a list when the nomenclature is a fixed time
[Python] Make sure the received function is a user-defined function
When a local variable with the same name as a global variable is defined in the function
What does the last () in a function mean in Python?
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
The value of meta when specifying a function with no return value in Dask dataframe apply
[Small story] A painstaking measure when you have to execute a function before import in Python
Get the value of a specific key up to the specified index in the dictionary list in Python
Use Heroku in python to notify Slack when a specific word is muttered on Twitter
A function that divides iterable into N pieces in Python
A memo when face is detected with Python + OpenCV quickly
A memo when creating a directed graph using Graphviz in Python
Grayscale image is displayed as a color image in OpenCV / Python
To return char * in a callback function using ctypes in Python
How to get the last (last) value in a list in Python
A memo of writing a basic function in Python using recursion
When "No changes detected" is displayed in python3 manage.py makemigrations
Try running a function written in Python using Fn Project
Take a screenshot in Python
Python execution time measurement memo
Use callback function in Python