README.md
1# ttictoc
2Time execution of blocks of code.
3
4##
5Tested against python 3.6, python 3.7, and 3.8
6
7## How to install
8From pip
9```
10pip install ttictoc
11```
12or download this repo and do
13```
14pip install .
15```
16
17## TicToc
18The easiest way to time something is with `tic` and `toc`
19
20```python
21import time
22from ttictoc import tic,toc
23tic()
24time.sleep(1)
25elapsed = toc()
26print('Elapsed time:',elapsed)
27```
28
29You can execute multiple tocs in a matlab-like fashon
30```
31import time
32from ttictoc import tic,toc
33tic()
34for i in range(2):
35 tic()
36 time.sleep(1)
37 elapsed = toc()
38 print('[IN LOOP] Elapsed time:',elapsed)
39print('[OUT LOOP] Elapsed time:',toc())
40```
41
42## Timer Class
43It works just like `tic`,`toc`.
44```python
45import time
46from ttictoc import Timer
47
48# Simple
49t = Timer()
50t.start()
51time.sleep(1)
52elapsed = t.stop()
53print('Elapsed time:',elapsed)
54
55
56# Nested
57t.start()
58for i in range(2):
59 t.start()
60 time.sleep(1)
61 elapsed = t.stop()
62 print('[IN LOOP] Elapsed time:',elapsed)
63print('[OUT LOOP] Elapsed time:',t.stop())
64```
65
66## Context manager
67You can also use it as context manager
68```python
69import time
70from ttictoc import Timer
71
72# Default
73with Timer():
74 time.sleep(1)
75
76# With out verbose
77with Timer(verbose=False) as T:
78 time.sleep(1)
79print('Elapsed time:',T.elapsed)
80
81# With default verbose message
82with Timer(verbose_msg=f'[User msg][{time.time()}] Elapsed time: {{}}'):
83 time.sleep(1)
84```
85
86## Deactivating matlab-like nesting
87You can deactivate the matlab-like nesting. In this case calling start will update the global starting time for toc. However, you can have nested tics by giving a `key` to start and stop.
88```python
89import time
90from ttictoc import Timer,tic2,toc2
91
92tic2()
93for i in range(2):
94 tic2()
95 time.sleep(1)
96 elapsed = toc2()
97 print('[IN LOOP] Elapsed time:',elapsed)
98print('[OUT LOOP] Elapsed time:',toc2())
99
100t = Timer(matlab_like=False)
101t.start()
102time.sleep(1)
103t.start() # Restarts the starting point
104time.sleep(1)
105elapsed = t.stop()
106print('Elapsed time:',elapsed) # ~1 second
107
108# Nested
109t.start(key='Init')
110for i in range(2):
111 t.start(key=i)
112 time.sleep(1)
113 elapsed = t.stop(key=i)
114 print('[IN LOOP] Elapsed time:',elapsed)
115print('[OUT LOOP] Elapsed time:',t.stop('Init'))
116
117
118print('\n[OUT LOOP][Init] Elapsed time:',t.stop('Init'))
119print('[OUT LOOP][0] Elapsed time:',t.stop(0))
120print('[OUT LOOP][1] Elapsed time:',t.stop(1))
121```
122
123## Specify timing method
124By default, `Timer` (and `tic`,`toc`) use `timeit.default_timer`. However, the timing function can be selected as follow.
125```python
126import time
127from ttictoc import Timer
128t = Timer(func_time=time.clock)
129t.start()
130time.sleep(5)
131elapsed = t.stop()
132print('Elapsed time:',elapsed)
133```
134