Python | How to calculate the program

Code # 1:

# Using the time module

import time

 
# class definition

class Timer:

 

def __ init __ ( self , func = time. perf_counter):

self . elapsed = 0.0

self ._ func  = func

self ._ start = None

 
# starting the module

def start ( self ):

if self ._ start is not None :

raise RuntimeError ( `Already started` )

self ._ start = self ._ func ()

 
# stop the timmer

def stop ( self ):

if self ._ start is None :

raise RuntimeError ( `Not started` )

end = self ._ func ()  

self . elapsed + = end - self ._ start

self ._ start = None

 
# Reset Timmer

def reset ( self ):

self . elapsed = 0.0

@property

  

def running ( self ):

return self ._ start is not None

 

def __ enter __ ( self ):

self . start ()

return self

 

def __ exit __ ( self , * args):

self . stop ()

We can start, stop or reset this timer using this class as needed for the user to keep track of the total elapsed time in the elapsed time attribute. For this it is mentioned in the code below —

Code # 2:

# using the class Timer ()

def countdown (n):

while n & gt;  0 :

n - = 1

 
# Usage 1: Explicit start / stop

time = Timer ()

 
# Start
time.start ()

countdown ( 1000000 )

 
# stop
time.stop ()

print (time.elapsed)

 
# Usage 2: as a context manager
with time:

  countdown ( 1000000 )

 

print (time.elapsed)

 
with Timer () as t2:

countdown ( 1000000 )

 

print (t2.elapsed)

  • The above code gives a very simple yet very useful class for measuring time and keeping track of the elapsed time. 
    It also shows how to maintain the context management protocol and the with statement.
  • The main function of timing is a problem when executing timing functions. Since the accuracy of time measurements made with functions such as time.time () or time.clock () varies depending on the operating system.
  • The highest resolution timer available on the system, by contrast, is used by time.perf_counter () .

To count the CPU time used by the process is instead used by time.process_time () , as explained in the code below:

Code # 3:

t = Timer (time.process_time)

with t:

countdown ( 1000000 )

print (t.elapsed)

Like time.perf_counter () so and time.process_time () return “time” in fractions of a second. To understand the results, call the functions twice and calculate the time difference, since the actual time does not really matter.