0

I need to find a way of speeding up the following Python code, not by just using some kind of package, but by using a different method. I can only see that a for loop is going to work for a problem of this kind.

import time
start_time = time.clock() #Set the start time of the program to be the current time

Nlist = [10**2, 10**3, 10**4, 10**5, 10**6, 10**7, 10**8] #The values of N we are summing to

for k in range(len(Nlist)): #Repeating the loop for the amount of elements in our list
    x = 0.
    y = 0. #Set initial values for x and y

    for i in range(1,Nlist[k]+1): #Summing over the various values of N (separately) in our list 
        x = 1./i #The summand 
        y += x #Keep adding 1/i for i=1,...,N i.e. our desired result

end_time = time.clock()

print('')
print('Time taken: {} seconds'.format(end_time - start_time)) #Prints time taken to run program

Here, I need to sum the harmonic series up to different values, namely N. The above code takes around 25 seconds to execute.

Is there a better way of doing this?

Wasi
  • 1,473
  • 3
  • 16
  • 32
  • Different method? Well..you are just adding a harmonic series of 1 + 1/2 + 1/3 + .. 1/n there is a mathematical solution for that. – Nf4r Oct 08 '16 at 10:23
  • Is there a reason for the outer `k` loop? I guess you only use it's last iteration, right? I believe removing that should give you about 11.11% speed. – zvone Oct 08 '16 at 10:36
  • Also, putting everything into a function, so that local variables are used instead of globals will give you a big performance improvement – zvone Oct 08 '16 at 10:46
  • @zvone The reason I've included the outer `k` loop is to iterate through `Nlist`, which means I can tabulate the sums in one go (I excluded this from the post for the sake of brevity). Thank you for the tip on using a function. – George Wilson Oct 08 '16 at 11:09
  • @zvone I used your tip by putting everything into a function, it improved the execution time by 10 seconds. Can you explain to me why this has such a significant performance increase? – George Wilson Oct 08 '16 at 14:10
  • @Will See this question: http://stackoverflow.com/q/11241523/389289 – zvone Oct 08 '16 at 15:14

0 Answers0