Welcome, guest | Sign In | My Account | Store | Cart

import PythonTimer

t = PythonTimer.TickTockTimer()

t.StartTimer()

t.GetTime()

3.9744668006896973

t.Pause()

t.UnPause()

Python, 41 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/python

#(c) 2011 , Narendra Sisodiya , narendra@narendrasisodiya.com 
#    Saturday, 09 April 2011

#
#   Released under MIT License
#

import time

class TickTockTimer:

	def StartTimer(self):
		self.TimerOffset = time.time()
		self.LastTicked = 0
		self.TimeWhenItWasPaused = 0
		self.paused = False
	
	def Tick(self):
		if self.paused is False:
			NewTicked = time.time() - self.TimerOffset
			diff = NewTicked - self.LastTicked
			self.LastTicked = NewTicked
			return diff
		else:
			print "Cannot Tick, Timer is paused"

	def GetTime(self):
		if self.paused is True:
			return self.TimeWhenItWasPaused
		else:
			return time.time() - self.TimerOffset
		
	def Pause(self):
		self.TimeWhenItWasPaused = time.time() - self.TimerOffset
		self.paused = True

	def UnPause(self):
		self.TimerOffset = time.time() - self.TimeWhenItWasPaused
		self.paused = False

7 comments

A. Polino 13 years ago  # | flag

You should use 'is' for comparing boolean values ;)

Thanks for guiding me ! I am new to Python ! I am learning it.

I have made changes !

Leon 13 years ago  # | flag

suggestion: handle condition that user call GetTime without StartTimer will be more robust. Reset timer

@Leon -- Actually, StartTimer is needed because user can start timer at any time. So we can have precise starting point in our code. Also, Did you noticed, that if you call StartTimer again, it will behave like a ResetTimer. Let me know, what you think on this, may you write code what changes you want to have ?

Wu Yan 13 years ago  # | flag

Leon means if the user call t.GetTime() without calling t.StartTimer() first, your program will get an error

Can somebody submit code to handle this ?? I am noob to python coding..

Created by Narendra Sisodiya on Sat, 9 Apr 2011 (MIT)
Python recipes (4591)
Narendra Sisodiya's recipes (1)

Required Modules

Other Information and Tasks