OS | macOS Sierra |
---|---|
CPU | 2.3 GHz Intel Core i7 |
memory | 16 GB 1600 MHz DDR3 |
Python version | 2.7.10 |
time.time ()
before and after the function call to measure the execution time by the differencedis
module to check the bytecodedef add(list_x, list_y):
list_x = list_x + list_y
return list_x
def inplace(list_x, list_y):
list_x += list_y
return list_x
list_a = [[0 for x in range(10000)] for y in range(10000)]
list_b = [[0 for x in range(10000)] for y in range(10000)]
add(list_a, list_b)
Execution time: 0.000458
id(list_a): 4391953400 -> 5530614960
------ dis.dis(add) ------
8 0 LOAD_FAST 0 (list_a)
3 LOAD_FAST 1 (list_b)
6 BINARY_ADD
7 STORE_FAST 0 (list_a)
9 10 LOAD_FAST 0 (list_a)
13 RETURN_VALUE
inplace(list_a, list_b)
Execution time: 0.000285
id(list_a): 5530614960 -> 5530614960
------ dis.dis(inplace) ------
44 0 LOAD_FAST 0 (list_a)
3 LOAD_FAST 1 (list_b)
6 INPLACE_ADD
7 STORE_FAST 0 (list_a)
45 10 LOAD_FAST 0 (list_a)
13 RETURN_VALUE
add | inplace | result | |
---|---|---|---|
Execution time | 0.000458 | 0.000285 | in place is faster |
Bytecode difference | BINARY_ADD | INPLACE_ADD | You can see that it has changed even with bytecode |
id(list_a) | There is a change | No change | add is created as a new object and replace is assigned a value to the same object. |
I had never been aware of the internal movements of both parties, so I investigated it myself. As long as I'm embarrassed when I was thinking, "Let's do it together!"
Recommended Posts