The results that @chepner mentioned are correct, Python can take longer to run the code in the console, but once the code is compiled the results are the same.
To make sure that this is correct, I created the following code also inspired by the answer from @knifer:
from time import time
from numpy import average,std
x = 1
xyzabcdexyzabcdefghidjakeldkjlkfghidjakeldkjlk = 1
short_runs = 0
long_runs = 0
for _ in range(int(2e7)):
t0 = time()
if x:
pass
short_runs += time() - t0
t0 = time()
if xyzabcdexyzabcdefghidjakeldkjlkfghidjakeldkjlk:
pass
long_runs += time() - t0
print('Runtime results:')
print(f"Small variable runs : (sum = {short_runs:.3f})")
print(f"Long variable runs : (sum = {long_runs :.3f})")
The code I propose is somewhat different, in the sense that the trial runs for the long and the short variable names are intertwined, such that any differences caused by underlying OS processes are minimized.
The results of the code vary depending on whether you copy-paste
the code into a Python console, or you call the code as a program (python trial_runs.py
). Runs using copy-paste
tend to be slower using long variables names, whereas calling the code as a program yields identical running times.
PS. The actual running times change all the time for me (in one direction or the other), so it's hard to report exact values. Even the long variable names can sometimes run faster, although this is very rare on the Python console. The biggest conclusion is that any differences are really small either way :)