How does one can determine the runtime of the following algorithm

54 views Asked by At
for n in range (1, n):
   for j in range(1, n+1):
       k = 1
       while k <= j:
           sumfunc()
           k *= 42

(Python code, meaning from 1 to n) How would one determine the numbers of calls of somefunc() and thus the runtime of this algorithm, if somefunc() would be the influencing part?

Other problems of this type I just converted to some summation and solved it, but this one is a bit trickier.

I noticed that until n = 41 everything is linear but after that log42(n) gets involved, but I don‘t know how to use this fact.

1

There are 1 answers

1
Andreas Hinderberger On

You technically just need to get a timestamp before and after the code execution and then subtract the before from the after timestamp to get the execution time of your code snippet:

import time

t0 = time.time()

for n in range (1, n):
   for j in range(1, n+1):
      k = 1
      while k <= j:
         sumfunc()
         k *= 42

t1 = time.time()

total = t1-t0