Skip to main content

Time parts of your code easily.

Project description

ttictoc

Time execution of blocks of code.

TocToc

The easiest way to time something is with tic and toc

from ttictoc import tic,toc
tic() # Start timing
# some code
elapsed = toc() # Gets the elapsed time until this moment
print('Elapsed time:',elapsed)

You can execute multiple tocs and will be linked to the tic time. Also, each time tic is executed the time holded by tic will be updated.

import time
from ttictoc import tic,toc
tic() # Start timing
time.sleep(1)
tic() # Reset the starting time
time.sleep(1)
print(toc()) # Prints ~1 seconds
time.sleep(1)
print(toc()) # Prints ~2 seconds

Timer Class

The Timer class can be used to have a single and multiple timers. Examples seen with tic,toc are also valid with Timer start,stop

import time
from ttictoc import Timer

# General timer
t = Timer()
t.start() # Starts the general timer
time.sleep(1)
elapsed = t.stop()
print('Elapsed time:',elapsed)

# Multiple timers
t.start('t0')
for i in range(2):
  tname = 't'+str(i+1)
  t.start(tname)
  time.sleep(1)
  elapsed = t.stop(tname)
  print('[INSIDE LOOP][{}] Elapsed time: {}'.format(tname,elapsed))
t.stop('t0')

print('[OUTSIDE LOOP][{}] Elapsed time: {}'.format('t0',t.elapsed['t0']))
print('[OUTSIDE LOOP][{}] Elapsed time: {}'.format('t1',t.elapsed['t1']))
print('[OUTSIDE LOOP][{}] Elapsed time: {}'.format('t2',t.elapsed['t2']))

Context manager

You can also use it as context manager

import time
from ttictoc import Timer

# Default
with Timer():
  time.sleep(1)

# With out verbose
with Timer(verbose=False) as T:
  time.sleep(1)
print('Elapsed time:',T.elapsed)

# With default verbose message
with Timer(verbose_msg=f'[User msg][{time.time()}] Elapsed time: {{}}'):
  time.sleep(1)

Specify timing method

By default, Timer (and tic,toc) use timeit.default_timer. However, the timing function can be selected as follow.

import time
from ttictoc import Timer
t = Timer(func_time=time.clock)
t.start()
time.sleep(5)
elapsed = t.stop()
print('Elapsed time:',elapsed)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ttictoc-0.5.0.tar.gz (3.5 kB view hashes)

Uploaded source

Built Distribution

ttictoc-0.5.0-py3-none-any.whl (5.3 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page