简体   繁体   中英

Does making python more compact, make it more efficient?

Ignoring code readability, is it worth removing redundant variables?

Eg. converting this code:

seconds = (milisec / 1000) % 60
minutes = milisec // (1000 * 60)
name = "{:>3}-{:0>5.2f}".format(minutes, seconds)

into:

name = "{:>3}-{:0>5.2f}".format(
    milisec // (1000 * 60), # minutes
    (milisec / 1000) % 60,  # seconds
    )

In term of execution time, the compact code is slighlty faster than the long code. A quick evaluation could be this:

在此处输入图像描述

That being said, the readability of the code matters . It is one of the milestones of Python code. Debugging, maintenance, team working (just to name a few) take advantage of a better code readability.

Creating variables take a little place in memory, so it would be faster if you don't do so. However, it is a really small difference.

Yes, your second piece of code, as you say more compact, will be slightly more efficient as assigning to variables correspond to some machine instructions.

from timeit import timeit

def function():

    milisec = 173000

    seconds = (milisec / 1000) % 60
    minutes = milisec // (1000 * 60)
    name = "{:>3}-{:0>5.2f}".format(minutes, seconds)


print(timeit(stmt='function()', setup='from __main__ import function', ))



def function2():
    milisec = 173000
    name = "{:>3}-{:0>5.2f}".format(
    milisec // (1000 * 60), # minutes
    (milisec / 1000) % 60,  # seconds
    )

print(timeit(stmt='function2()', setup='from __main__ import function2', ))

see some difference on one run of batches (in seconds)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM