CnR
CnR

Reputation: 371

How long is the running time of code in python

I was required to calculate approximately how long will it take to an avg computer to run this code, assuming the speed of the loop is linear (my teacher told me to assume it, I know it's not true, but we are beginners so..):

num = 2**100
cnt = 0
import time
t0 = time.clock()
for i in range(num):
    cnt = cnt+1

t1 = time.clock()
print("running time: ", t1-t0, " sec") 

I waited for 3 hours and didn't get anything, so, as people advised me to do, I calculated it for a smaller input: 2**20. This took 0.24478681215692052 seconds.

Now, I tried to continue the calculation in 2 ways that I think must get me the SAME result, but they aren't.

  1. if I assume the speed of the loop is linear, to calculate 2**100 I simply have to calculate (0.24478681215692052)^5, because (2**20)**5 = 2**100.

    the result I got was: 0.000878901251447358 seconds (which is really not logical)

  2. I tried another way:

    • 2**20 - 0.24478681215692052 sec
    • 2**100 - ?

    and multiply like this:

    2**100 * 0.24478681215692052 / 2**20
    

    and got: 296101054897497890198453.29788130608283648 seconds by using this calculator for big numbers.

how is it possible that I got 2 different answers? and neither seem really logical?

Upvotes: 0

Views: 365

Answers (1)

fryday
fryday

Reputation: 397

    x**y * x**z = x**(y + z)

Lets prove it

    x**y + x**z = (x * ...y times... * x) * (x * ...z times... * x) = 
    = (x * ...y+1 times... * x) * (x * ...z-1 times... * x) = 
    = ... = (x * ...y+z times... * x) = x**(y + z)

That's why

    2**100 = 2**(20 + 80) = 2**20 * 2**80

So,

    f(2**100) = f(2**20) * 2**80 = 0.24478681215692052 * 0.24478681215692052 =
    = 2.9592909751765742e+23 seconds

Upvotes: 1

Related Questions