This question is mostly about optimizing a script's performance by switching the order of an if-statement and a for-loop. I have a code that is a bit similar to the one below (I removed all unnecessary bits for simplification purposes). I wrote the three alternatives that came to mind. Version 1:
for rowindex in range(400):
for columnindex in range(10):
exec(f'{something}1 = ...')
if comparisonbool:
exec(f'{something}2 = ...')
Version 2:
for rowindex in range(400):
if comparisonbool:
for columnindex in range(10):
exec(f'{something}1 = ...')
exec(f'{something}2 = ...')
else:
for columnindex in range(10):
exec(f'{something}1 = ...')
Version 3:
if comparisonbool:
for rowindex in range(400):
for columnindex in range(10):
exec(f'{something}1 = ...')
exec(f'{something}2 = ...')
else:
for rowindex in range(400):
for columnindex in range(10):
exec(f'{something}1 = ...')
So, while I find version 1 to look nicer, I was wondering if versions 2 or 3 would result in a significantly better performance. My reasoning is that, in version 3, the if-statement if checked only once and then the code runs based on its result. In version 2, it is checked 400 times. In version 1, it is checked 4000 times
However, I tried timing it by using time.perf_counter() [I ran it directly before and after my loops and calculated the difference between the two]. I timed 6 runs for each of the three versions and got the following average run times: Tv1: 0.56s , Tv2: 0.50s, Tv3: 0.53s I believe the differences in timing are insignificant and caused by random variables, since repeating my experiment gives different results (sometimes v3 is the fastest, other times v1, etc...)
My question is: given the insignificant performance differences, should I just stick to version 1, or would versions 2 or 3 be considered for some reason more "pythonic"?
I tried searching for posts that discuss this by comparing different ordering options, but wasn't able to find any. I consider myself to be relatively new to python and this is my first post on this website so I hope my question is formulated well and easily understood.
Aucun commentaire:
Enregistrer un commentaire