Python without the switch (select) syntax may use a dictionary instead, A note about its execution time.
-** 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.
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