. , , , , , , , , .
, . ,
return f(g(i(1, 2), j(3, 4)), h(k(5, 6), l(7, 8)))
. - : , PEP-008, , , .
, , . : ** , .
- Python . , , , . , , . , , , .
from __future__ import print_function, division
from timeit import Timer
import dis
def cuberoot_1line(number):
return str(pow(number, 1/3))
def cuberoot_1lineA(number):
return str(number ** (1/3))
def cuberoot_3line(number):
cube_root = pow(number, 1/3)
string_cube_root = str(cube_root)
return string_cube_root
funcs = (
cuberoot_1line,
cuberoot_3line,
cuberoot_1lineA,
)
def show_dis():
''' Show the disassembly for each function '''
print('Disassembly')
for func in funcs:
fname = func.func_name
print('\n%s' % fname)
dis.dis(func)
print()
nums = (1, 2, 8, 27, 64)
def verify():
''' Verify that the functions actually perform as intended '''
print('Verifying...')
for func in funcs:
fname = func.func_name
print('\n%s' % fname)
for n in nums:
print(n, func(n))
print()
def time_test(loops, reps):
''' Print timing stats for all the functions '''
print('Timing tests\nLoops = %d, Repetitions = %d' % (loops, reps))
for func in funcs:
fname = func.func_name
print('\n%s' % fname)
setup = 'from __main__ import nums, %s' % fname
t = Timer('[%s(n) for n in nums]' % fname, setup)
r = t.repeat(reps, loops)
r.sort()
print(r)
show_dis()
verify()
time_test(loops=10000, reps=5)
Disassembly
cuberoot_1line
27 0 LOAD_GLOBAL 0 (str)
3 LOAD_GLOBAL 1 (pow)
6 LOAD_FAST 0 (number)
9 LOAD_CONST 3 (0.33333333333333331)
12 CALL_FUNCTION 2
15 CALL_FUNCTION 1
18 RETURN_VALUE
cuberoot_3line
33 0 LOAD_GLOBAL 0 (pow)
3 LOAD_FAST 0 (number)
6 LOAD_CONST 3 (0.33333333333333331)
9 CALL_FUNCTION 2
12 STORE_FAST 1 (cube_root)
34 15 LOAD_GLOBAL 1 (str)
18 LOAD_FAST 1 (cube_root)
21 CALL_FUNCTION 1
24 STORE_FAST 2 (string_cube_root)
35 27 LOAD_FAST 2 (string_cube_root)
30 RETURN_VALUE
cuberoot_1lineA
30 0 LOAD_GLOBAL 0 (str)
3 LOAD_FAST 0 (number)
6 LOAD_CONST 3 (0.33333333333333331)
9 BINARY_POWER
10 CALL_FUNCTION 1
13 RETURN_VALUE
Verifying...
cuberoot_1line
1 1.0
2 1.25992104989
8 2.0
27 3.0
64 4.0
cuberoot_3line
1 1.0
2 1.25992104989
8 2.0
27 3.0
64 4.0
cuberoot_1lineA
1 1.0
2 1.25992104989
8 2.0
27 3.0
64 4.0
Timing tests
Loops = 10000, Repetitions = 5
cuberoot_1line
[0.29448986053466797, 0.29581117630004883, 0.29786992073059082, 0.30267000198364258, 0.36836600303649902]
cuberoot_3line
[0.29777216911315918, 0.29979610443115234, 0.30110907554626465, 0.30503296852111816, 0.3104550838470459]
cuberoot_1lineA
[0.2623140811920166, 0.26727819442749023, 0.26873588562011719, 0.26911497116088867, 0.2725379467010498]
2 , Python 2.6.6 Linux.