0

I read this topic because I forget a method I found in the net few month ago, and I don't know why I can't find it today, it was very simple and works good but...


So I tried one method but I think it doesn't work good or maybe my computer which is 5 years old is better than today's computer...

import time

debut=time.clock()

def t(n): 
    aaa=[]
    b=n-1
    c=0
    if n==0 or n==1:
        return 1
    else:
        while n != 1: 
            if n % 2==0: 
                n=n//2
                aaa.append(n)
            else: 
                n = n+b
                aaa.append(n)
    return [b,b+1]+aaa, len(aaa)+2

fin=time.clock()

print(t(100000),fin-debut)

For n=10.000.000 i can count in my head approx 5 secondes and computer always return 3.956927685067058e-06 ... can someone explain me ?


And the method I found, used this from time import perf_counter as pc

And I had to return print(pc()-t)

If someone can enlighten me because i really don't remember the method.

Thank you in advance

Community
  • 1
  • 1
ParaH2
  • 519
  • 1
  • 4
  • 21

2 Answers2

2

Look at the timeit module, https://docs.python.org/3.0/library/timeit.html.

you would set yours something like...

time = Timer( "t(100000)", "from __main__ import t")
print("time: ", timer.timeit(number=1000))
User
  • 14,131
  • 2
  • 40
  • 59
Mitch
  • 183
  • 1
  • 12
0

You are measuring the time it takes to define the function. This will measure the execution of the function:

import time

def t(n): 
    aaa=[]
    b=n-1
    c=0
    if n==0 or n==1:
        return 1
    else:
        while n != 1: 
            if n % 2==0: 
                n=n//2
                aaa.append(n)
            else: 
                n = n+b
                aaa.append(n)
    return [b,b+1]+aaa, len(aaa)+2

start = time.time()
value = t(100000)
end = time.time()

duration = end - start
print(value, duration)
User
  • 14,131
  • 2
  • 40
  • 59
  • No it doesn't. The method i found just use time module and need to instructions.. – ParaH2 Jun 21 '15 at 19:03
  • Thank you well i will make an other account in Euler project i find this method there where the players tell their solution, i just solved the 5 first problems so the answer will not be difficult to seek :) – ParaH2 Jun 21 '15 at 20:44