You are viewing a single comment's thread from:

RE: Python Code Speed Improvement

in #python7 years ago

I can't agree with what you wrote in "Style vs Performance". Your example seems like a classic example of premature optimization.

Especially this sentence:

whenever you can, and style doesn’t matter

Style matters a lot. Assuming that what you write is not a single-use program that'll be forgotten after execution, your code will be read much, much more often than written or refactored. This is even more true when you collaborate with others - then you can either focus on style first, or write terribly styled code and spend thrice as time on writing comments or docs, or be a jerk to your coworkers and write just the terribly styled code.

And as for your example, I measured it:

$ python -m timeit 'array=[1,1,1,1,1,1,1,1,1,1]
sum=0
for a in range(0,10):
  sum+=array[a]'
1000000 loops, best of 3: 0.802 usec per loop

$ python -m timeit 'array=[1,1,1,1,1,1,1,1,1,1]
sum=array[0]+array[1]+array[2]+array[3]+array[4]+array[5]+array[6]+array[7]+array[8]+array[9]'
1000000 loops, best of 3: 0.333 usec per loop

0.802µs vs 0.333µs. Yeah, it's slower. Does it matter? Most likely not. What matters is that second example is much less readable and more error-prone (which you even admit yourself).

Sort:  

Yes but it matters to me though, I was analyzing the market and speed is very crucial, a default calculation takes like 2 hours.

Besides the long string can be automatically written too:

string="sum=array[0]"
for i in range(1,9+1):
       string+="+array["+str(i)+"]"

print (string)

This way we avoid typos and mistakes.

...and then you'd have to eval that long string to get an array which would be even slower, not to say completely unsafe 😉

If your calculation takes 2 hours, then I'd say replacing for loops with manually typed array accesses is not the best place to optimize. Most likely something else takes long to finish.

Have you tried profiling your code?