user_noname_00
user_noname_00

Reputation: 369

Optimizing Python code for efficiency

Profiling this code shows the bulk of the time is spent on the log operation. Is there another way to write this in Python 3 for more efficiency? Replacing the loop with a list comprehension was actually less efficient and so was map because of lambdas.

def log_total(data): 
    total = 0.0   
    log = log(data) 
    for i in range(10000): 
        total += log/(i+1)  
    return total

Thanks!

Upvotes: 3

Views: 286

Answers (2)

user1389938
user1389938

Reputation:

Can write with lambda in on line, like this:

total = lambda data: log(data) * sum(1.0 / i for i in xrange(1, 10001))

I used Python 2.7.3.

Upvotes: 0

Blender
Blender

Reputation: 298106

I'd factor the log out of your summation and cache your sum:

harmonic_series = sum(1. / i for i in range(1, 10001))  # Thanks, @mgilson

def log_total(data): 
    return log(data) * harmonic_series

You could also use PyPy to speed it up even more.

Upvotes: 9

Related Questions