-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathProfiling.html
More file actions
654 lines (622 loc) · 46.1 KB
/
Profiling.html
File metadata and controls
654 lines (622 loc) · 46.1 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
<!DOCTYPE html>
<html class="writer-html5" lang="en" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Performance and Profiling — Programming in Python 7.0 documentation</title>
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<!--[if lt IE 9]>
<script src="../_static/js/html5shiv.min.js"></script>
<![endif]-->
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/js/theme.js"></script>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="prev" title="Threaded Web Scraper" href="../exercises/threaded_downloader.html" />
</head>
<body class="wy-body-for-nav">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search" style="background: #4b2e83" >
<a href="../index.html">
<img src="../_static/UWPCE_logo_full.png" class="logo" alt="Logo"/>
</a>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<p class="caption" role="heading"><span class="caption-text">Topics in the Program</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../topics/01-setting_up/index.html">1. Setting up your Environment</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/02-basic_python/index.html">2. Basic Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/03-recursion_booleans/index.html">3. Booleans and Recursion</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/04-sequences_iteration/index.html">4. Sequences and Iteration</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/05-text_handling/index.html">5. Basic Text Handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/06-exceptions/index.html">6. Exception Handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/07-unit_testing/index.html">7. Unit Testing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/08-dicts_sets/index.html">8. Dictionaries and Sets</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/09-files/index.html">9. File Handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/10-modules_packages/index.html">10. Modules and Packages</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/11-argument_passing/index.html">11. Advanced Argument Passing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/12-comprehensions/index.html">12. Comprehensions</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/13-intro_oo/index.html">13. Intro to Object Oriented Programing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/14-magic_methods/index.html">14. Properties and Magic Methods</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/15-subclassing/index.html">15. Subclassing and Inheritance</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/16-multiple_inheritance/index.html">16. Multiple Inheritance</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/17-functional_programming/index.html">17. Introduction to Functional Programming</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/18-advanced_testing/index.html">18. Advanced Testing</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../topics/99-extras/index.html">19. Extra Topics</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="Pep8.html">Coding Style and Linting</a></li>
<li class="toctree-l2"><a class="reference internal" href="CodeReviews.html">Code Reviews</a></li>
<li class="toctree-l2"><a class="reference internal" href="PersistanceAndSerialization.html">Persistence and Serialization</a></li>
<li class="toctree-l2"><a class="reference internal" href="Unicode.html">Unicode in Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="IteratorsAndGenerators.html">Iterators and Generators</a></li>
<li class="toctree-l2"><a class="reference internal" href="Decorators.html">Decorators</a></li>
<li class="toctree-l2"><a class="reference internal" href="../exercises/mailroom/mailroom-decorator.html">Mailroom – Decoratoring it</a></li>
<li class="toctree-l2"><a class="reference internal" href="ContextManagers.html">Context Managers</a></li>
<li class="toctree-l2"><a class="reference internal" href="../exercises/context-managers-exercise.html">A Couple Handy Context Managers</a></li>
<li class="toctree-l2"><a class="reference internal" href="MetaProgramming.html">Metaprogramming</a></li>
<li class="toctree-l2"><a class="reference internal" href="../exercises/mailroom/mailroom-meta.html">Mailroom – metaprogramming it!</a></li>
<li class="toctree-l2"><a class="reference internal" href="Logging.html">Logging and the logging module</a></li>
<li class="toctree-l2"><a class="reference internal" href="Debugging.html">Debugging</a></li>
<li class="toctree-l2"><a class="reference internal" href="NoSQL.html">No SQL Databases</a></li>
<li class="toctree-l2"><a class="reference internal" href="GraphDatabases.html">Graph Databases</a></li>
<li class="toctree-l2"><a class="reference internal" href="Concurrency.html">Concurrent Programming</a></li>
<li class="toctree-l2"><a class="reference internal" href="Async.html">Asychronous Programming</a></li>
<li class="toctree-l2"><a class="reference internal" href="Coroutines.html">Notes on Coroutines</a></li>
<li class="toctree-l2"><a class="reference internal" href="ThreadingMultiprocessing.html">Threading and multiprocessing</a></li>
<li class="toctree-l2"><a class="reference internal" href="../exercises/threaded_downloader.html">Threaded Web Scraper</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="#">Performance and Profiling</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" style="background: #4b2e83" >
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">Programming in Python</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content style-external-links">
<div role="navigation" aria-label="Page navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html" class="icon icon-home"></a> »</li>
<li><a href="../topics/99-extras/index.html"><span class="section-number">19. </span>Extra Topics</a> »</li>
<li>Performance and Profiling</li>
<li class="wy-breadcrumbs-aside">
<a href="../_sources/modules/Profiling.rst.txt" rel="nofollow"> View page source</a>
</li>
</ul><div class="rst-breadcrumbs-buttons" role="navigation" aria-label="Sequential page navigation">
<a href="../exercises/threaded_downloader.html" class="btn btn-neutral float-left" title="Threaded Web Scraper" accesskey="p"><span class="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
</div>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="performance-and-profiling">
<span id="profiling"></span><h1>Performance and Profiling<a class="headerlink" href="#performance-and-profiling" title="Permalink to this headline"></a></h1>
<div class="section" id="today-s-topics">
<h2>Today’s topics<a class="headerlink" href="#today-s-topics" title="Permalink to this headline"></a></h2>
<ul class="simple">
<li><p>Determining performance objectives</p></li>
<li><p>Measuring performance a.k.a. profiling</p></li>
<li><p>Performance optimizations</p></li>
</ul>
<div class="section" id="what-is-software-profiling">
<h3>What is Software Profiling<a class="headerlink" href="#what-is-software-profiling" title="Permalink to this headline"></a></h3>
<p>The act of using instrumentation to objectively measure the performance
of your application</p>
<p>“Performance” can be a measure of any of the following:</p>
<ul class="simple">
<li><p>resource use (CPU, memory)</p></li>
<li><p>frequency or duration of function calls</p></li>
<li><p>wall clock execution time of part or all of your application</p></li>
</ul>
<p>Collecting this data involves instrumenting the code. In Python, this
happens at runtime.</p>
<p>The instrumentation creates overhead, so it has a performance cost</p>
<p>The output data (a “profile”) will be a statistical summary of the
execution of functions</p>
</div>
<div class="section" id="an-optimization-strategy">
<h3>An optimization strategy<a class="headerlink" href="#an-optimization-strategy" title="Permalink to this headline"></a></h3>
<ol class="arabic simple">
<li><p>Write the code for maintainability / readability</p></li>
<li><p>Test for correctness</p></li>
<li><p>Collect profile data</p></li>
<li><p>If it is fast enough, quit. Your job here is done.</p></li>
<li><p>Else optimize the most expensive parts based on profiling data</p></li>
<li><p>Repeat from 2)</p></li>
</ol>
<p>Programmers waste enormous amounts of time thinking about, or
worrying about, the speed of noncritical parts of their programs,
and these attempts at efficiency actually have a strong negative
impact when debugging and maintenance are considered. We should
forget about small efficiencies, say about 97% of the time:</p>
<p><em>premature optimization is the root of all evil.</em></p>
<p>–Donald Knuth</p>
<p><a class="reference external" href="http://c2.com/cgi/wiki?PrematureOptimization">http://c2.com/cgi/wiki?PrematureOptimization</a></p>
<p><a class="reference external" href="http://c2.com/cgi/wiki?ProfileBeforeOptimizing">http://c2.com/cgi/wiki?ProfileBeforeOptimizing</a></p>
</div>
<div class="section" id="steps-to-better-performance">
<h3>Steps to better performance<a class="headerlink" href="#steps-to-better-performance" title="Permalink to this headline"></a></h3>
<p>(In order of importance)</p>
<ol class="arabic simple">
<li><p>Efficient Algorithms (big O, etc…)</p></li>
<li><p>Appropriate Python data types, etc.</p></li>
<li><p>Appropriate Python style</p></li>
<li><p>Specialized packages (numpy, scipy)</p></li>
<li><p>Calling external packages</p></li>
<li><p>Extending with C/C++/Fortran/Cython</p></li>
</ol>
</div>
<div class="section" id="big-o-notation">
<h3>Big O notation<a class="headerlink" href="#big-o-notation" title="Permalink to this headline"></a></h3>
<p>The efficiency of an algorithm is often described in “big O” notation.</p>
<p>The letter O is used because the growth rate of a function is also
referred to as Order of the function</p>
<p>It describes how an algorithm behaves in terms of resource use as a
function of amount of input data</p>
<p>O(1) - (Constant performance) Execution time stays constant regardless of how much data is supplied</p>
<ul class="simple">
<li><p>Example: adding to a dict</p></li>
</ul>
<p>O(n) - Time goes up linearly with number of items.</p>
<ul class="simple">
<li><p>Example: scanning lists</p></li>
</ul>
<p>O(n<sup>2</sup>) - Time goes up quadratically with number of items.</p>
<ul class="simple">
<li><p>Example: bubble sort, worst case</p></li>
</ul>
<p>O(log(n)) - goes up with the log of number of items</p>
<ul class="simple">
<li><p>Example: bisection search</p></li>
</ul>
<img alt="../_images/big_o.png" src="../_images/big_o.png" />
<p><strong>log?</strong> you expect me to remember that math???</p>
<p>Let’s think about that a bit….</p>
<p>Anyone know what a bisection search is?</p>
<p>Why is that O(log(n))?</p>
<div class="line-block">
<div class="line"><br /></div>
</div>
<p>Reference:</p>
<p><a class="reference external" href="https://wiki.python.org/moin/TimeComplexity">https://wiki.python.org/moin/TimeComplexity</a></p>
</div>
<div class="section" id="measuring-time-with-a-stopwatch">
<h3>Measuring time with a stopwatch<a class="headerlink" href="#measuring-time-with-a-stopwatch" title="Permalink to this headline"></a></h3>
<p>One way to measure performance is with a stopwatch.</p>
<p>Start the clock when a unit of code such as a function begins, and stop
it when the code returns</p>
<p>This is a the simplest method, and we can instrument our code to start
and stop the clock.</p>
<p>Like most timing benchmarks, data obtained is valid only for the
particular test environment (machine/OS/Python version..)</p>
<p>Relative timings may be valid across systems, but can also diverge</p>
<p>For instance a run on a machine with fast network and slow disk may
produce much different results on a system with slow network and fast
disk</p>
</div>
<div class="section" id="time-clock-time-time">
<h3><code class="docutils literal notranslate"><span class="pre">time.clock()</span></code> : <code class="docutils literal notranslate"><span class="pre">time.time()</span></code><a class="headerlink" href="#time-clock-time-time" title="Permalink to this headline"></a></h3>
<p>Using the time module as a profiling decorator</p>
<p><code class="docutils literal notranslate"><span class="pre">time.time()</span></code> returns the unix system time (wall clock time)</p>
<p><code class="docutils literal notranslate"><span class="pre">time.clock()</span></code> returns the CPU time of the current process</p>
<p>Precision is system dependent</p>
<p>Quite coarse, but can capture the big picture</p>
<p>See <a class="reference download internal" download="" href="../_downloads/762d8b297a01879edef7304147b250de/timer_test.py"><code class="xref download docutils literal notranslate"><span class="pre">/examples/profiling/timer/timer_test.py</span></code></a></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
<span class="k">def</span> <span class="nf">timer</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">timer</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="sd">"""a decorator which prints execution time of the decorated function"""</span>
<span class="n">t1</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="n">t2</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"-- executed </span><span class="si">%s</span><span class="s2"> in </span><span class="si">%.4f</span><span class="s2"> seconds"</span> <span class="o">%</span> <span class="p">(</span><span class="n">func</span><span class="o">.</span><span class="n">func_name</span><span class="p">,</span> <span class="p">(</span><span class="n">t2</span> <span class="o">-</span> <span class="n">t1</span><span class="p">)))</span>
<span class="k">return</span> <span class="n">result</span>
<span class="k">return</span> <span class="n">timer</span>
<span class="nd">@timer</span>
<span class="k">def</span> <span class="nf">expensive_function</span><span class="p">():</span>
<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="nd">@timer</span>
<span class="k">def</span> <span class="nf">less_expensive_function</span><span class="p">():</span>
<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">.02</span><span class="p">)</span>
<span class="n">expensive_function</span><span class="p">()</span>
<span class="n">less_expensive_function</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="timeit">
<h3>timeit<a class="headerlink" href="#timeit" title="Permalink to this headline"></a></h3>
<p>Used for testing small bits of code</p>
<p>Use to test hypotheses about efficiency of algorithms and Python idioms</p>
<p>Will run the given statement many times and calculate the average
execution time</p>
<p>Can be run from the command line:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">timeit</span> <span class="s1">'"-".join(str(n) for n in range(100))'</span>
</pre></div>
</div>
<p><a class="reference external" href="https://docs.python.org/3.5/library/timeit.html">https://docs.python.org/3.5/library/timeit.html</a></p>
<p>See the <code class="docutils literal notranslate"><span class="pre">timeit.py</span></code> source:</p>
<p><a class="reference external" href="https://hg.python.org/cpython/file/3.5/Lib/timeit.py">https://hg.python.org/cpython/file/3.5/Lib/timeit.py</a></p>
</div>
<div class="section" id="timeit-command-line-interface">
<h3><code class="docutils literal notranslate"><span class="pre">timeit</span></code> command line interface<a class="headerlink" href="#timeit-command-line-interface" title="Permalink to this headline"></a></h3>
<p>options</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">-nN</span></code>: execute the given statement N times in a loop. If this value is
not given, a fitting value is chosen.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">-rR</span></code>: repeat the loop iteration R times and take the best result.
Default: 3</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">-t</span></code>: use time.time to measure the time, which is the default on Unix.
This function measures wall time.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">-c</span></code>: use time.clock to measure the time, which is the default on
Windows and measures wall time. On Unix, resource.getrusage is used
instead and returns the CPU user time.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">-pP</span></code>: use a precision of P digits to display the timing result.
Default: 3</p></li>
</ul>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>$ python -m timeit -n <span class="m">1000</span> -t <span class="s2">"len([x**2 for x in range(1000)])"</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">timeit</span></code> can also be imported as a module</p>
<p><a class="reference external" href="http://docs.python.org/3/library/timeit.html#timeit.timeit">http://docs.python.org/3/library/timeit.html#timeit.timeit</a></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="n">stmt</span><span class="o">=</span><span class="s1">'pass'</span><span class="p">,</span>
<span class="n">setup</span><span class="o">=</span><span class="s1">'pass'</span><span class="p">,</span>
<span class="n">timer</span><span class="o">=<</span><span class="n">default</span> <span class="n">timer</span><span class="o">></span><span class="p">,</span>
<span class="n">number</span><span class="o">=</span><span class="mi">1000000</span><span class="p">)</span>
</pre></div>
</div>
<p>The setup kwarg contains a string of Python code to execute before the
loops start, so that code is not part of the test</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">timeit</span>
<span class="n">statement</span> <span class="o">=</span> <span class="s2">"char in text"</span>
<span class="n">setup_code</span> <span class="o">=</span> <span class="s2">"""text = "sample string";char = "g" """</span>
<span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="n">statement</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="n">setup_code</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="timeit-via-ipython-magic">
<h3><code class="docutils literal notranslate"><span class="pre">timeit</span></code> via iPython magic<a class="headerlink" href="#timeit-via-ipython-magic" title="Permalink to this headline"></a></h3>
<p>Note that all that setup_code stuff is kind of a pain.</p>
<p>iPython has your back (again)</p>
<div class="highlight-ipython notranslate"><div class="highlight"><pre><span></span><span class="o">%</span><span class="k">timeit</span> pass
<span class="n">u</span> <span class="o">=</span> <span class="kc">None</span>
<span class="o">%</span><span class="k">timeit</span> u is None
<span class="o">%</span><span class="k">timeit</span> -r 4 u == None
<span class="kn">import</span> <span class="nn">time</span>
<span class="o">%</span><span class="k">timeit</span> -n1 time.sleep(2)
<span class="o">%</span><span class="k">timeit</span> -n 10000 "f" in "food"
</pre></div>
</div>
<p><a class="reference external" href="http://ipython.readthedocs.io/en/stable/interactive/magics.html?#magic-timeit">timeit magic</a></p>
</div>
<div class="section" id="exercise">
<h3>Exercise<a class="headerlink" href="#exercise" title="Permalink to this headline"></a></h3>
<p>We just tried determining if a character exists in a string:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">statement</span> <span class="o">=</span> <span class="s2">"'f' in 'food'"</span>
<span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="n">statement</span><span class="p">)</span>
</pre></div>
</div>
<p>Run timeit with an alternative statement:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">statement2</span> <span class="o">=</span> <span class="s2">"'food'.find('f') >= 0"</span>
<span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="n">statement2</span><span class="p">)</span>
</pre></div>
</div>
<p>Which is faster? Why?</p>
</div>
<div class="section" id="getting-more-detailed-with-profiling">
<h3>Getting more detailed with Profiling<a class="headerlink" href="#getting-more-detailed-with-profiling" title="Permalink to this headline"></a></h3>
<p>That kind of timing is only useful if you know what part of the code you want to optimize.</p>
<p>But what if you know your program is “slow”, but don’t know where is is spending the time?</p>
<p><strong>Do not Guess!</strong> – you will often be wrong, and you don’t want to waste time optimizing the wrong thing.</p>
<p><em>Really</em> – even very experienced programmers are often wrong about where the bottlenecks are.</p>
<p>You really need to profile to be sure.</p>
<p>Also: take into account the entire run-time: does it make sense to optimize an initialization routine that takes a few seconds before a multi-hour run?</p>
<p>A profiler takes measurements of runtime performance and summarizes results into a profile report</p>
<p>Reported metrics could include</p>
<ul class="simple">
<li><p>Memory used over time</p></li>
<li><p>Memory allocated per function</p></li>
<li><p>Frequency of function calls</p></li>
<li><p>Duration of function calls</p></li>
<li><p>Cumulative time spent in subfunction calls</p></li>
</ul>
</div>
<div class="section" id="python-s-built-in-profilers">
<h3>Python’s built-in profilers<a class="headerlink" href="#python-s-built-in-profilers" title="Permalink to this headline"></a></h3>
<p>Python comes with a couple profiling modules</p>
<ul class="simple">
<li><p>profile - older, pure Python. If you need to extend the profiler,
this might be good. Otherwise, it’s slow.</p></li>
<li><p>cProfile - same API as profile, but written in C for less overhead</p></li>
</ul>
<p><strong>You almost always want to use ``cProfile``</strong></p>
<p><a class="reference external" href="https://docs.python.org/3/library/profile.html">https://docs.python.org/3/library/profile.html</a></p>
</div>
<div class="section" id="cprofile">
<h3>cProfile<a class="headerlink" href="#cprofile" title="Permalink to this headline"></a></h3>
<p>Can be run as a module on an entire application</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>python -m cProfile <span class="o">[</span>-o output_file<span class="o">]</span> <span class="o">[</span>-s sort_order<span class="o">]</span> read_bna.py
<span class="m">11111128</span> <span class="k">function</span> calls <span class="k">in</span> <span class="m">8</span>.283 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno<span class="o">(</span><span class="k">function</span><span class="o">)</span>
<span class="m">1</span> <span class="m">0</span>.000 <span class="m">0</span>.000 <span class="m">0</span>.000 <span class="m">0</span>.000 integrate.py:1<span class="o">()</span>
<span class="m">11111110</span> <span class="m">2</span>.879 <span class="m">0</span>.000 <span class="m">2</span>.879 <span class="m">0</span>.000 integrate.py:1<span class="o">(</span>f<span class="o">)</span>
<span class="o">[</span>....<span class="o">]</span>
</pre></div>
</div>
<ul class="simple">
<li><p>ncalls: number of calls</p></li>
<li><p>tottime: total time spent in function, excluding time in sub-functions</p></li>
<li><p>percall: tottime / ncalls</p></li>
<li><p>cumtime: total time spent in function, including time in sub-functions</p></li>
<li><p>percall: cumtime / ncalls</p></li>
<li><p>filename:lineno – location of function</p></li>
</ul>
</div>
<div class="section" id="analyzing-profile-data">
<h3>Analyzing profile data<a class="headerlink" href="#analyzing-profile-data" title="Permalink to this headline"></a></h3>
<p>Output to a binary dump with -o <filename></p>
<p>While doing performance work, save your profiles for comparison later</p>
<p>This helps ensure that any changes do actually increase performance</p>
<p>A profile dump file can be read with <code class="docutils literal notranslate"><span class="pre">pstats</span></code></p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>python -m pstats
</pre></div>
</div>
<p>Gives you a command line interface</p>
<p>(help for help…)</p>
</div>
<div class="section" id="pstats">
<h3><code class="docutils literal notranslate"><span class="pre">pstats</span></code><a class="headerlink" href="#pstats" title="Permalink to this headline"></a></h3>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">cProfile</span> <span class="o">-</span><span class="n">o</span> <span class="n">prof_dump</span> <span class="o">./</span><span class="n">read_bna</span><span class="o">.</span><span class="n">py</span>
<span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">pstats</span>
<span class="o">%</span> <span class="n">read</span> <span class="n">prof_dump</span>
<span class="c1"># show stats:</span>
<span class="n">prof_dump</span><span class="o">%</span> <span class="n">stats</span>
<span class="c1"># only the top 5 results:</span>
<span class="n">prof_dump</span><span class="o">%</span> <span class="n">stats</span> <span class="mi">5</span>
<span class="c1"># sort by cumulative time:</span>
<span class="n">prof_dump</span><span class="o">%</span> <span class="n">sort</span> <span class="n">cumulative</span>
<span class="c1"># shorten long filenames for display:</span>
<span class="n">prof_dump</span><span class="o">%</span> <span class="n">strip</span>
<span class="c1"># show results again:</span>
<span class="n">prof_dump</span><span class="o">%</span> <span class="n">stats</span> <span class="mi">5</span>
</pre></div>
</div>
<p>pstats also has method calls:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pstats</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">pstats</span><span class="o">.</span><span class="n">Stats</span><span class="p">(</span><span class="s1">'prof_dump'</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="s1">'calls'</span><span class="p">,</span> <span class="s1">'cumulative'</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>
<span class="c1"># Output can be restricted via arguments to print_stats().</span>
<span class="c1"># Each restriction is either an integer (to select a count of lines),</span>
<span class="c1"># a decimal fraction between 0.0 and 1.0 inclusive (to select a percentage of lines),</span>
<span class="c1"># or a regular expression (to pattern match the standard name that is printed.</span>
<span class="c1"># If several restrictions are provided, then they are applied sequentially.</span>
</pre></div>
</div>
</div>
<div class="section" id="id1">
<h3>Analyzing profile data<a class="headerlink" href="#id1" title="Permalink to this headline"></a></h3>
<p>Inspect only your local code with regular expression syntax:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pstats</span>
<span class="n">prof</span> <span class="o">=</span> <span class="n">pstats</span><span class="o">.</span><span class="n">Stats</span><span class="p">(</span><span class="s1">'prof_dump'</span><span class="p">)</span>
<span class="n">prof</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="s1">'cumulative'</span><span class="p">)</span>
<span class="n">prof</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="s1">'^./[a-z]*.py:'</span><span class="p">)</span>
</pre></div>
</div>
<p>I tend to write little scripts like this so I don’t have to remember the commands.</p>
</div>
<div class="section" id="exercise-example">
<h3>Exercise / Example<a class="headerlink" href="#exercise-example" title="Permalink to this headline"></a></h3>
<p>Real world example:</p>
<p><code class="docutils literal notranslate"><span class="pre">Examples/profiling/bna_reader/read_bna.py</span></code></p>
<p>BNA is a (old) text file format for holding geospatial data.</p>
<p>We were using some old code of mine that read these files, generated an internal data structure of polygons, and rendered them to a PNG.</p>
<p>As these files got big – this process started getting really slow.</p>
<p>I had already optimized the file reading code a lot – so could we do better?</p>
<blockquote>
<div><ul class="simple">
<li><p>I assumed not</p></li>
</ul>
</div></blockquote>
<p>One of my team ran the profiler and identified the bottleneck – and yes – we could do better – a lot.</p>
<p>Let’s try that out now.</p>
</div>
</div>
<div class="section" id="some-other-tools-to-consider">
<h2>Some other tools to consider<a class="headerlink" href="#some-other-tools-to-consider" title="Permalink to this headline"></a></h2>
<ul class="simple">
<li><p>For better visualizing</p></li>
<li><p>For C extensions</p></li>
<li><p>For memory Profiling</p></li>
</ul>
<div class="section" id="snakeviz">
<h3>SNAKEVIZ<a class="headerlink" href="#snakeviz" title="Permalink to this headline"></a></h3>
<p>A graphical profile viewer for Python</p>
<p><a class="reference external" href="https://jiffyclub.github.io/snakeviz/">https://jiffyclub.github.io/snakeviz/</a></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">pip</span> <span class="n">install</span> <span class="n">snakeviz</span>
</pre></div>
</div>
<p>Inspired by “Run Snake Run”: <a class="reference external" href="http://www.vrplumber.com/programming/runsnakerun/">http://www.vrplumber.com/programming/runsnakerun/</a></p>
<p>(which only works with Python 2.* for now)</p>
<img alt="../_images/snakeviz.png" src="../_images/snakeviz.png" />
</div>
<div class="section" id="line-profiler">
<h3>line profiler<a class="headerlink" href="#line-profiler" title="Permalink to this headline"></a></h3>
<p>Thus far, we’ve seen how to collect data on the performance of functions
as atomic units</p>
<p><code class="docutils literal notranslate"><span class="pre">line_profiler</span></code> is a module for doing line-by-line profiling of functions</p>
<p><code class="docutils literal notranslate"><span class="pre">line_profiler</span></code> ships with its own profiler, <code class="docutils literal notranslate"><span class="pre">kernprof.py</span></code>.</p>
<p>Enable line-by-line profiling with -l</p>
<p>Decorate the function you want to profile with <code class="docutils literal notranslate"><span class="pre">@profile</span></code> and run</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="c1"># the -v option will display the profile data immediately, instead</span>
<span class="c1"># of just writing it to <filename.py>.lprof</span>
$ kernprof -l -v integrate_main.py
<span class="c1"># load the output with</span>
$ python -m line_profiler integrate_main.py.lprof
</pre></div>
</div>
<p><a class="reference external" href="https://github.com/rkern/line_profiler">https://github.com/rkern/line_profiler</a></p>
</div>
<div class="section" id="qcachegrind-kcachegrind">
<h3>qcachegrind / kcachegrind<a class="headerlink" href="#qcachegrind-kcachegrind" title="Permalink to this headline"></a></h3>
<p>profiling tool based on Valgrind:</p>
<p><a class="reference external" href="http://kcachegrind.sourceforge.net/html/Valgrind.html">http://kcachegrind.sourceforge.net/html/Valgrind.html</a></p>
<p>a runtime instrumentation framework for Linux/x86</p>
<p>Can be used with Python profile data with a profile format conversion</p>
<p>Doesn’t give all the information that a native valgrind run would
provide</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># convert python profile to calltree format</span>
<span class="n">pip</span> <span class="n">install</span> <span class="n">pyprof2calltree</span>
<span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">cProfile</span> <span class="o">-</span><span class="n">o</span> <span class="n">dump</span><span class="o">.</span><span class="n">profile</span> <span class="n">integrate_main</span><span class="o">.</span><span class="n">py</span>
<span class="n">pyprof2calltree</span> <span class="o">-</span><span class="n">i</span> <span class="n">dump</span><span class="o">.</span><span class="n">profile</span> <span class="o">-</span><span class="n">o</span> <span class="n">dump</span><span class="o">.</span><span class="n">callgrind</span>
</pre></div>
</div>
<p><a class="reference external" href="http://kcachegrind.sourceforge.net/cgi-bin/show.cgi/KcacheGrindCalltreeFormat">http://kcachegrind.sourceforge.net/cgi-bin/show.cgi/KcacheGrindCalltreeFormat</a></p>
</div>
<div class="section" id="profiling-c-extensions">
<h3>Profiling C extensions<a class="headerlink" href="#profiling-c-extensions" title="Permalink to this headline"></a></h3>
<p>Google Performance Tools:</p>
<p><a class="reference external" href="https://code.google.com/p/gperftools/">https://code.google.com/p/gperftools/</a></p>
<p>can be used to profile C extensions</p>
<p>Just call ProfilerStart and ProfilerStop with ctypes around the code you
want to profile</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ctypes</span>
<span class="n">libprof</span> <span class="o">=</span> <span class="n">ctypes</span><span class="o">.</span><span class="n">CDLL</span><span class="p">(</span><span class="s1">'/usr/local/lib/libprofiler.0.dylib'</span><span class="p">)</span>
<span class="n">libprof</span><span class="o">.</span><span class="n">ProfilerStart</span><span class="p">(</span><span class="s1">'/tmp/out.prof'</span><span class="p">)</span>
<span class="kn">import</span> <span class="nn">numpy</span>
<span class="n">a</span><span class="o">=</span><span class="n">numpy</span><span class="o">.</span><span class="n">linspace</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">100</span><span class="p">)</span>
<span class="n">a</span><span class="o">*=</span><span class="mi">32432432</span>
<span class="n">libprof</span><span class="o">.</span><span class="n">ProfilerStop</span><span class="p">(</span><span class="s1">'/tmp/out.prof'</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="c1"># convert the profile to qcachegrind's format with google's pprof tool</span>
$ pprof --callgrind ~/virtualenvs/uwpce/lib/python2.7/site-packages/numpy/core/multiarray.so out.prof > output.callgrind
$ qcachegrind output.callgrind
</pre></div>
</div>
</div>
<div class="section" id="memory-profilers">
<h3>memory profilers<a class="headerlink" href="#memory-profilers" title="Permalink to this headline"></a></h3>
<p>There aren’t any great ones</p>
<p>One option is heapy, which comes with Guppy, a Python environment for
memory profiling</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">guppy</span> <span class="kn">import</span> <span class="n">hpy</span><span class="p">;</span> <span class="n">hp</span><span class="o">=</span><span class="n">hpy</span><span class="p">()</span>
<span class="n">hp</span><span class="o">.</span><span class="n">doc</span><span class="o">.</span><span class="n">heap</span>
<span class="n">hp</span><span class="o">.</span><span class="n">heap</span><span class="p">()</span>
<span class="o">%</span><span class="n">run</span> <span class="n">define</span><span class="o">.</span><span class="n">py</span> <span class="n">Robot</span>
<span class="n">hp</span><span class="o">.</span><span class="n">heap</span><span class="p">()</span>
</pre></div>
</div>
<p>Others:</p>
<p><a class="reference external" href="https://pypi.python.org/pypi/memory_profiler">https://pypi.python.org/pypi/memory_profiler</a></p>
<p><a class="reference external" href="http://mg.pov.lt/objgraph/">http://mg.pov.lt/objgraph/</a></p>
<p><a class="reference external" href="https://launchpad.net/meliae">https://launchpad.net/meliae</a></p>
<p><a class="reference external" href="http://pythonhosted.org/Pympler/muppy.html">http://pythonhosted.org/Pympler/muppy.html</a></p>
<p><a class="reference external" href="http://jmdana.github.io/memprof/">http://jmdana.github.io/memprof/</a></p>
</div>
</div>
<div class="section" id="boosting-python-performance">
<h2>Boosting Python performance<a class="headerlink" href="#boosting-python-performance" title="Permalink to this headline"></a></h2>
<p>There are ways to better structure your Python code to improve performance</p>
<div class="section" id="a-few-key-approaches">
<h3>A few key approaches<a class="headerlink" href="#a-few-key-approaches" title="Permalink to this headline"></a></h3>
<ul class="simple">
<li><p>Overhead in function/method runtime lookup can be significant for
small frequent calls.</p></li>
<li><p>inlining code or caching function results might help.</p></li>
<li><p>Python string handling idioms: use <code class="docutils literal notranslate"><span class="pre">"".join(list_of_strings)</span></code> rather
than sequential calls to += See <code class="docutils literal notranslate"><span class="pre">examples/strings/str_concat.py</span></code> and
<code class="docutils literal notranslate"><span class="pre">str_comprehensions.py</span></code></p></li>
<li><p>using list comprehensions, generator expressions, <code class="docutils literal notranslate"><span class="pre">or</span> <span class="pre">map()</span></code> instead of
for loops can be faster (see <code class="docutils literal notranslate"><span class="pre">data_aggregation/loops.py</span></code>)</p></li>
<li><p>Leverage existing domain specific C extension libraries, for instance
numpy for fast array operations.</p></li>
<li><p>Rewrite expensive code as C modules. Use ctypes, Cython, SWIG, …</p></li>
</ul>
<p><a class="reference external" href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips/">http://wiki.python.org/moin/PythonSpeed/PerformanceTips/</a></p>
</div>
<div class="section" id="managing-memory">
<h3>Managing memory<a class="headerlink" href="#managing-memory" title="Permalink to this headline"></a></h3>
<p>Don’t forget memory:</p>
<p>Processors are fast</p>
<p>It can take longer to push the memory around than do the computation</p>
<p>So keep in mind for big data sets:</p>
<p>Use the right data structures</p>
<p>Use efficient algorithms</p>
<p>Use generators and iterators, rather than lists.</p>
<p>Use iterators to pull in the data you need from databases, sockets,
files, …</p>
</div>
<div class="section" id="distraction-pygame">
<h3>Distraction: pyGame<a class="headerlink" href="#distraction-pygame" title="Permalink to this headline"></a></h3>
<p>There is a nice profiling example that uses PyGame:</p>
<p><a class="reference external" href="http://www.pygame.org/hifi.html">http://www.pygame.org/hifi.html</a></p>
<p>Which you can install from binaries:</p>
<p>Windows:
<a class="reference external" href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame">http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame</a></p>
<p>(you want the wheel file for the python you are running: probably cp35)</p>
<p>Anaconda Python:</p>
<p>First install miniconda. Then you can install pygame from anaconda.org.</p>
<p><a class="reference external" href="https://anaconda.org/cogsci">https://anaconda.org/cogsci</a></p>
</div>
<div class="section" id="a-more-complex-profile">
<h3>A more complex profile<a class="headerlink" href="#a-more-complex-profile" title="Permalink to this headline"></a></h3>
<p>The amount of data in the previous example is readable, so now we’ll
look at the output from a more complex application:
examples/profiling/pygame/swarm.py</p>
<p>This program consists of calculating the gravitational acceleration of
bodies around a central mass and displaying them</p>
<p>There are two major consumers of resources: one is our own code
calculating the physics, the other is pygame drawing the results on the
screen</p>
<p>Our goal is to figure out whether the major bottleneck is in our own
logic or in the pygame operations</p>
<p>A simple way to get data for our own code is</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">cProfile</span> <span class="n">swarm</span><span class="o">.</span><span class="n">py</span> <span class="o">&></span> <span class="o">/</span><span class="n">tmp</span><span class="o">/</span><span class="n">output</span><span class="o">.</span><span class="n">txt</span>
<span class="n">grep</span> <span class="n">swarm</span><span class="o">.</span><span class="n">py</span> <span class="o">/</span><span class="n">tmp</span><span class="o">/</span><span class="n">output</span><span class="o">.</span><span class="n">txt</span>
</pre></div>
</div>
</div>
<div class="section" id="questions">
<h3>Questions?<a class="headerlink" href="#questions" title="Permalink to this headline"></a></h3>
</div>
</div>
</div>
</div>
</div>
<footer><div class="rst-footer-buttons" role="navigation" aria-label="Footer">
<a href="../exercises/threaded_downloader.html" class="btn btn-neutral float-left" title="Threaded Web Scraper" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>© Copyright 2020, University of Washington, Natasha Aleksandrova, Christopher Barker, Brian Dorsey, Cris Ewing, Christy Heaton, Jon Jacky, Maria McKinley, Andy Miles, Rick Riehle, Joseph Schilz, Joseph Sheedy, Hosung Song. Creative Commons Attribution-ShareAlike 4.0 license.</p>
</div>
Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a
<a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script>
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html>