2

I am new to Python programming. I started working on Project Euler this morning and I wanted to find out how long it takes to execute my solution. I have searched online for a solution to my

import time

class Solution(object):
    def fibonacci(self,limit):
        sum = 0
        current = 1
        next = 2
        while(current <= limit):
            if  current % 2==0:
                sum += current
            current, next = next, current + next

        return  str(sum)

if __name__ == "__main__":
    start = time.clock()
    solution = Solution().fibonacci(4000000)
    elapsed = time.clock()-start
    print("Solution: %s"%(solution))
    print("Time: %s seconds"%(elapsed))

Output:
Solution: 4613732
Time: 2.006085436846098e-05 seconds


import time

class Solution(object):
    def fibonacci(self,limit):
        sum = 0
        current = 1
        next = 2
        while(current <= limit):
            if  current % 2==0:
                sum += current
            current, next = next, current + next

        return  str(sum)

if __name__ == "__main__":
    start = time.time()
    solution = Solution().fibonacci(4000000)
    elapsed = time.time()-start
    print("Solution: %s"%(solution))
    print("Time: %s seconds"%(elapsed))

Output:
Solution: 4613732
Time: 0.0 seconds


My question is

  1. Is the time calculated above correct?
  2. What is the difference between time.time() vs time.clock(). If I use time.time() I get 0.0 as time.
200_success
  • 7,286
  • 1
  • 43
  • 74
  • Migrated from Code Review because the question is not asking for open-ended suggestions for improvement, but rather asks for an explanation about a specific programming issue. – 200_success Sep 03 '16 at 17:41

1 Answers1

2

In the Python time module, time.clock() measures the time since the first call of the function in seconds, and time.time() measures the time since January 1st, 1970, in seconds.

time.clock() is generally more precise, so using this is what I recommend. This is the reason why you have the tiny result in the first example, rounded down to zero in the second example.

StardustGogeta
  • 3,331
  • 2
  • 18
  • 32