Question:
I try to optimize this simple code to reduce execution time.
I can't propose anything to help the solution. I have got other codes that reduce the time, but I can not do it on this one.
def squaresum(n):
"""Returns the sum of squares of first n natural numbers.
Parameters:
n (int): positive integer.
Returns:
(int): sum of squares from 1 to n (inclusive).
"""
total = 0
operands = []
for i in range(1, n + 1):
aux = pow(i, 2)
operands.append(aux)
for op in operands:
total = total + op
return total
I have observed execution times per line with:
%load_ext line_profiler
%lprun -f squaresum squaresum(2)
Answer:
The time of your first for loop can be reduced with a list compression and for the sum you can use the function sum(iterable)
%load_ext line_profiler
def squaresum(n):
"""Returns the sum of squares of first n natural numbers.
Parameters:
n (int): positive integer.
Returns:
(int): sum of squares from 1 to n (inclusive).
"""
operands = [pow(1,2) for i in range(1, n+1)]
total = sum(operands)
return total
%lprun -f squaresum squaresum(2)
Where for %lprun -f squaresum squaresum(10000000)
the total time is Total time: 4.21687 s
Which is more than good unlike your previous code that took about 24s