Code performance analysis » History » Version 1
Rafael Bailon-Ruiz, 2020-11-03 12:26
1 | 1 | Rafael Bailon-Ruiz | h1. Code performance analysis |
---|---|---|---|
2 | |||
3 | h2. Execution time |
||
4 | |||
5 | h3. Unscientific way → time module: One sample |
||
6 | |||
7 | |||
8 | Do not forget to configure your logger to the DEBUG level |
||
9 | <pre><code class="python"> |
||
10 | from functools import wraps |
||
11 | from time import time |
||
12 | |||
13 | def timing(f): |
||
14 | @wraps(f) |
||
15 | def wrap(*args, **kw): |
||
16 | ts = time() |
||
17 | result = f(*args, **kw) |
||
18 | te = time() |
||
19 | _logger.debug('func:%r took: %2.4fs args:[%r, %r] ', f.__name__, te-ts, args, kw) |
||
20 | return result |
||
21 | return wrap |
||
22 | |||
23 | @timing |
||
24 | def my_func(a,b,c): |
||
25 | d = [] |
||
26 | return a + b + c |
||
27 | </code></pre> |
||
28 | |||
29 | |||
30 | h3. Scientific way → timeit module |
||
31 | |||
32 | It runs a function multiple times to statisitically determine the execution time |
||
33 | |||
34 | h2. Memory |
||
35 | |||
36 | To analyze the dynamic usage of memory within a function use the <code class="python">memory_profiler</code> python package. It will give you a line-by-line report of memory usage. |
||
37 | <pre><code class="python"> |
||
38 | from memory_profiler import profile |
||
39 | |||
40 | @profile |
||
41 | def my_func(a,b,c): |
||
42 | d = [b + (c * i) for i in range(len(a))] |
||
43 | return d |
||
44 | </code></pre> |
||
45 | |||
46 | |||
47 | <code class="python"></code> |