-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync-python.html
861 lines (753 loc) · 42.7 KB
/
async-python.html
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>A Pythonic Journey Into Concurrency – smarlowucf</title>
<!-- Meta -->
<meta name="description" content="smarlowucf – ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Social -->
<meta property="article:author" content="Sean Marlow" />
<meta property="article:section" content="Python" />
<meta property="article:published_time" content="2019-01-26" />
<meta property="og:type" content="article"/>
<meta property="og:title" content="A Pythonic Journey Into Concurrency"/>
<meta property="og:description" content="A look at concurrency in Python"/>
<meta property="og:site_name" content="smarlowucf" />
<meta property="og:url" content="https://smarlowucf.github.io/async-python.html"/>
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="A Pythonic Journey Into Concurrency">
<meta name="twitter:description" content="A look at concurrency in Python">
<meta name="twitter:url" content="https://smarlowucf.github.io/async-python.html">
<!-- Feed -->
<link rel="alternate" type="application/atom+xml" href="https://smarlowucf.github.io/feeds/all.atom.xml" title="smarlowucf Atom Feed" />
<link rel="alternate" type="application/atom+xml" href="https://smarlowucf.github.io/feeds/{slug}.atom.xml" title="smarlowucf Categories Atom Feed" />
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Open+Sans:regular,bold">
<link rel="stylesheet" type="text/css" href="https://smarlowucf.github.io/theme/css/w3.css">
<link rel="stylesheet" type="text/css" href="https://smarlowucf.github.io/theme/css/style.css">
<link rel="stylesheet" type="text/css" href="https://smarlowucf.github.io/theme/css/jqcloud.css">
<link rel="stylesheet" type="text/css" href="https://smarlowucf.github.io/theme/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="https://smarlowucf.github.io/theme/css/pygments.css">
<!-- Icon -->
<!-- JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://smarlowucf.github.io/theme/js/jqcloud.min.js"></script>
</head>
<body>
<div class="w3-row w3-card w3-white">
<header id="header">
<a href="https://smarlowucf.github.io" id="header-logo" title="Home">SM</a>
<nav id="header-menu">
<ul>
<li><a href="https://smarlowucf.github.io/pages/projects.html">Projects</a></li>
<li class="w3-bottombar w3-border-white w3-hover-border-green" ><a href="https://smarlowucf.github.io/category/booknotes.html">Booknotes</a></li>
<li class="w3-bottombar w3-border-white w3-hover-border-green" style="font-weight: bold;"><a href="https://smarlowucf.github.io/category/python.html">Python</a></li>
</ul>
</nav>
</header>
</div>
<br><br><br>
<article>
<header class="w3-container col-main">
<h1>A Pythonic Journey Into Concurrency</h1>
<div class="post-info">
<div class="w3-opacity w3-margin-right w3-margin-bottom" style="flex-grow: 1;">
<span><time datetime="2019-01-26T10:20:00-06:00">Sat 26 January 2019</time> in <a href="https://smarlowucf.github.io/category/python.html" title="All articles in category Python">Python</a></span>
</div>
<div>
<span class="w3-tag w3-light-grey w3-text-green w3-hover-green">
<a href="https://smarlowucf.github.io/tag/async.html" title="All articles with Async tag">#async</a>
</span>
<span class="w3-tag w3-light-grey w3-text-green w3-hover-green">
<a href="https://smarlowucf.github.io/tag/python.html" title="All articles with Python tag">#python</a>
</span>
</div>
</div>
</header>
<br>
<div class="col-main w3-container">
<section id="content">
<div class="section" id="synchronous-vs-asynchronous">
<h2>Synchronous vs Asynchronous</h2>
<dl class="docutils">
<dt><strong>Synchronous</strong></dt>
<dd>Sequential set of actions or tasks. One process at a time, when one
finishes the next starts.</dd>
<dt><strong>Asynchronous</strong></dt>
<dd>Processes or tasks can take place concurrently during execution of a
program.</dd>
<dt><strong>Concurrency</strong></dt>
<dd>When several computations are executed during overlapping time
periods. Concurrency does not necessarily mean parallelism.</dd>
</dl>
</div>
<div class="section" id="asynchronous">
<h2>Asynchronous</h2>
<div class="section" id="threads-sometimes">
<h3>Threads (Sometimes)</h3>
<p>Threads are lighter than processes however in Python they cannot run in
parallel. Due to the GIL (Global Interpreter Lock) threads should not be
used for CPU bound tasks. Using threads with CPU heavy tasks leads to
code that basically runs synchronously.</p>
<p>Threads do work well with I/O bound code though, since most of the time
is spent waiting on a response.</p>
</div>
<div class="section" id="processes">
<h3>Processes</h3>
<p>Processes are heavier than threads but do not have the same issue with
the GIL. Thus multi-processing works well for CPU and I/O bound code.</p>
<p>There are a few options in Python that provide multi-processing. But we
will focus on the asyncio event loop framework and async/await syntax.</p>
</div>
<div class="section" id="workers-celery-rq">
<h3>Workers (Celery, RQ)</h3>
<p>We won’t go into this option but it would mainly be useful with
distributed apps, web apps and/or service oriented projects. Celery and
RQ are distributed task queues which can concurrently run jobs with a
pool of workers. These can be either threads, processes or combination
of the two.</p>
<div class="section" id="how-does-the-code-compare">
<h4>How does the code compare?</h4>
</div>
</div>
</div>
<div class="section" id="synchronous">
<h2>Synchronous</h2>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">timeit</span>
<span class="k">def</span> <span class="nf">sleep</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Start sleep'</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="n">n</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Stop sleep'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">sleep</span><span class="p">(</span><span class="o">.</span><span class="mi">8</span><span class="p">)</span>
<span class="n">sleep</span><span class="p">(</span><span class="o">.</span><span class="mi">9</span><span class="p">)</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">main</span><span class="p">()</span>
<span class="n">elapsed</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Sync took </span><span class="si">%0.2f</span><span class="s1">s'</span> <span class="o">%</span> <span class="n">elapsed</span><span class="p">)</span>
</pre></div>
</td></tr></table> <div class="highlight"><pre><span></span>$ python sync_sleep.py
Start sleep
Stop sleep
Start sleep
Stop sleep
Sync took <span class="m">1</span>.70s
</pre></div>
<p>Each call to sleep function happens sequentially.</p>
</div>
<div class="section" id="multi-thread">
<h2>Multi-thread</h2>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 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</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">timeit</span>
<span class="kn">from</span> <span class="nn">threading</span> <span class="kn">import</span> <span class="n">Thread</span>
<span class="k">def</span> <span class="nf">sleep</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Start sleep'</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="n">n</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Stop sleep'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">s1</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">sleep</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="o">.</span><span class="mi">8</span><span class="p">,))</span>
<span class="n">s2</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">sleep</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="o">.</span><span class="mi">9</span><span class="p">,))</span>
<span class="n">s1</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="n">s2</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="n">s1</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
<span class="n">s2</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">main</span><span class="p">()</span>
<span class="n">elapsed</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Thread took </span><span class="si">%0.2f</span><span class="s1">s'</span> <span class="o">%</span> <span class="n">elapsed</span><span class="p">)</span>
</pre></div>
</td></tr></table> <div class="highlight"><pre><span></span>$ python thread_sleep.py
Start sleep
Start sleep
Stop sleep
Stop sleep
Thread took <span class="m">0</span>.90s
</pre></div>
<p>Both threads have been started, join waits for execution to finish.
Both threads start the sleep function concurrently.
Execution time is equal to longest sleep function call.</p>
</div>
<div class="section" id="multi-process-w-asyncio">
<h2>Multi-process w/ asyncio</h2>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">timeit</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">sleep</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Start sleep'</span><span class="p">)</span>
<span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Stop sleep'</span><span class="p">)</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">tasks</span> <span class="o">=</span> <span class="p">[</span><span class="n">sleep</span><span class="p">(</span><span class="o">.</span><span class="mi">8</span><span class="p">),</span> <span class="n">sleep</span><span class="p">(</span><span class="o">.</span><span class="mi">9</span><span class="p">)]</span>
<span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait</span><span class="p">(</span><span class="n">tasks</span><span class="p">)</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">elapsed</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Async took </span><span class="si">%0.2f</span><span class="s1">s'</span> <span class="o">%</span> <span class="n">elapsed</span><span class="p">)</span>
</pre></div>
</td></tr></table> <div class="highlight"><pre><span></span>$ python async_sleep.py
Start sleep
Start sleep
Stop sleep
Stop sleep
Async took <span class="m">0</span>.90s
</pre></div>
<ul class="simple">
<li>The <tt class="docutils literal">async def</tt> denotes this function as a coroutine. This also can
be denoted with the <tt class="docutils literal">@asyncio.coroutine</tt> decorator.</li>
<li>When we hit an await statement the future or coroutine is added to
event loop and we yield control back to the loop.</li>
<li>The wait function wraps the coroutines with ensure_future which
returns a future instance for each.</li>
<li>Ensures the loop is running until all the tasks finished.</li>
</ul>
</div>
<div class="section" id="asyncio">
<h2>Asyncio</h2>
<p>Asyncio provides an infrastructure for writing single-threaded
concurrent code using coroutines. The execution of coroutines is managed
via an event loop through the use of cooperative or non-preemptive
multitasking.</p>
<div class="section" id="coroutines">
<h3>Coroutines</h3>
<p>In Python a coroutine is a generator that can yield values and receive
values from the outside. This allows the function to pause execution
just lke a generator and yield control.</p>
<p>As noted above coroutines are denoted in one of two ways as of Python
3.5. Generator based using a decorator and <tt class="docutils literal">yield from</tt> as well as
natively using the keywords <tt class="docutils literal">async</tt>/<tt class="docutils literal">await</tt>.</p>
<blockquote>
<p><strong>Note</strong></p>
<p>Native coroutines cannot contain any <tt class="docutils literal">yield</tt> statements.</p>
</blockquote>
</div>
<div class="section" id="generators">
<h3>Generators</h3>
<p>Functions that can yield a value and pause execution. Control is
returned to the calling scope. In the case of asyncio this is the event
loop. A generator object is an iterable and has the <tt class="docutils literal">next</tt> function.
This is allows the calling function to iterate over it and get values
one by one.</p>
</div>
<div class="section" id="tasks-futures">
<h3>Tasks / Futures</h3>
<p>A future is like a promise. It is a place holder to say that a value
will exist in the future. In python you can await futures, tasks and
coroutines. When the future is finished it returns the value of the
underlying function or an exception.</p>
<p>A Task is a subclass of future that wraps a coroutine. When the
coroutine finishes, the result of the Task is realized.</p>
</div>
<div class="section" id="event-loop">
<h3>Event Loop</h3>
<p>An event loop runs constantly until it’s explicitly stopped. The asyncio
loop continuously iterates over a task queue. With each future the event
loop calls the <tt class="docutils literal">next</tt> function which picks up where it left off. When
another coroutine or future is called the active future is suspended and
cooperatively/voluntarily yields control. This is called a context
switch. The event loop then moves to the next task.</p>
</div>
<div class="section" id="async-await">
<h3>Async/await</h3>
<p>Async/await can be considered an API to access event loops. This is idea
is discussed by <a class="reference external" href="http://pyvideo.org/python-brasil-2015/keynote-david-beazley-topics-of-interest-python-asyncio.html">David
Beazley</a>.
The syntax is not tied directly to asyncio and can be used with other
event loop implementations such as Curio and Trio.</p>
<p>As of Python 3.5 the async/await syntax was added. This is similar to
the previous decorator based syntax but there are key differences.</p>
<p>A (native) <tt class="docutils literal">async def</tt> defined coroutine can only do two things,
<tt class="docutils literal">await</tt> and <tt class="docutils literal">return</tt>. An error is raised if a <tt class="docutils literal">yield</tt> is within a
native coroutine. The decorator based coroutine uses <tt class="docutils literal">yield from</tt>
instead of <tt class="docutils literal">await</tt>.</p>
</div>
</div>
<div class="section" id="other-libraries">
<h2>Other Libraries</h2>
<div class="section" id="curio">
<h3>Curio</h3>
<p>A library that’s similar to and can replace the asyncio event loop for
concurrent programming. It uses the same async/await syntax and
cooperative multitasking just like asyncio. However, the way it handles
events is very different and the API is much smaller.
<a class="reference external" href="https://curio.readthedocs.io/en/latest/">Curio</a> performs around 20%
faster than comparable asyncio code.</p>
</div>
<div class="section" id="trio">
<h3>Trio</h3>
<p><a class="reference external" href="https://trio.readthedocs.io/en/latest/index.html">Trio</a> is also an
async/await native I/O library for Python. Its main purpose is to help
you write programs that do multiple things at the same time with
parallelized I/O. Trio draws inspiration from many sources including
Dave Beazley’s Curio.</p>
<blockquote>
<p><strong>Note</strong></p>
<p>Trio is not production ready.</p>
</blockquote>
</div>
</div>
<div class="section" id="a-few-more-examples">
<h2>A Few More Examples</h2>
<div class="section" id="cpu-bound-synchronous">
<h3>CPU Bound Synchronous</h3>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">timeit</span>
<span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o"><</span> <span class="mi">2</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">fib</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="n">fib</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="mi">2</span><span class="p">)</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">fib</span><span class="p">(</span><span class="mi">33</span><span class="p">)</span>
<span class="n">fib</span><span class="p">(</span><span class="mi">34</span><span class="p">)</span>
<span class="n">elapsed</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Sync took </span><span class="si">%0.2f</span><span class="s1">s'</span> <span class="o">%</span> <span class="n">elapsed</span><span class="p">)</span>
</pre></div>
</td></tr></table> <div class="highlight"><pre><span></span>$ python sync_fib.py
Sync took <span class="m">2</span>.91s
</pre></div>
</div>
<div class="section" id="cpu-bound-multi-thread">
<h3>CPU Bound Multi-thread</h3>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 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</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">timeit</span>
<span class="kn">from</span> <span class="nn">threading</span> <span class="kn">import</span> <span class="n">Thread</span>
<span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o"><</span> <span class="mi">2</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">fib</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="n">fib</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="mi">2</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">f1</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">fib</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="mi">33</span><span class="p">,))</span>
<span class="n">f2</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">fib</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="mi">34</span><span class="p">,))</span>
<span class="n">f1</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="n">f2</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="n">f1</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
<span class="n">f2</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">main</span><span class="p">()</span>
<span class="n">elapsed</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Thread took </span><span class="si">%0.2f</span><span class="s1">s'</span> <span class="o">%</span> <span class="n">elapsed</span><span class="p">)</span>
</pre></div>
</td></tr></table> <div class="highlight"><pre><span></span>$ python thread_fib.py
Thread took <span class="m">2</span>.86s
</pre></div>
<p>Ended up taking about the same time as the synchronous code. Not
surprising since each thread is utilizing 100% CPU during execution.
The GIL blocks the threads from running concurrently.</p>
</div>
<div class="section" id="cpu-bound-multi-process-w-asyncio">
<h3>CPU Bound Multi-process w/ asyncio</h3>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">timeit</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o"><</span> <span class="mi">2</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="k">await</span> <span class="n">fib</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="k">await</span> <span class="n">fib</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="mi">2</span><span class="p">)</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">tasks</span> <span class="o">=</span> <span class="p">[</span><span class="n">fib</span><span class="p">(</span><span class="mi">33</span><span class="p">),</span> <span class="n">fib</span><span class="p">(</span><span class="mi">34</span><span class="p">)]</span>
<span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait</span><span class="p">(</span><span class="n">tasks</span><span class="p">)</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">elapsed</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Async took </span><span class="si">%0.2f</span><span class="s1">s'</span> <span class="o">%</span> <span class="n">elapsed</span><span class="p">)</span>
</pre></div>
</td></tr></table> <div class="highlight"><pre><span></span>$ python async_fib.py
Async took <span class="m">6</span>.34s
</pre></div>
<p>What!? Isn’t asyncio great for CPU bound concurrency? The problem
here is a bad algorithm and the overhead of context switching.
Because fib is recursive every call to a new fib coroutine adds a
task to the queue. This adds up quickly and requires an excessive
number of context switches.</p>
</div>
<div class="section" id="with-iterative-fibonacci-algorithm">
<h3>With Iterative Fibonacci Algorithm</h3>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="o">...</span>
<span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o"><</span> <span class="mi">2</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="n">fib</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">prev</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
<span class="n">prev</span><span class="p">,</span> <span class="n">fib</span> <span class="o">=</span> <span class="n">fib</span><span class="p">,</span> <span class="n">fib</span> <span class="o">+</span> <span class="n">prev</span>
<span class="o">...</span>
</pre></div>
</td></tr></table> <div class="highlight"><pre><span></span>$ python sync_fib_iter.py
Sync took <span class="m">1</span>.46s
$ python thread_fib_iter.py
Thread took <span class="m">1</span>.74s
$ python async_fib_iter.py
Async took <span class="m">0</span>.50s
</pre></div>
<p>Now we don’t have all of the context switches that come with a
recursive algorithm.</p>
</div>
<div class="section" id="asyncio-iterative-fibonacci-example-using-process-pool">
<h3>Asyncio Iterative Fibonacci Example Using Process Pool</h3>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 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</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">concurrent.futures</span>
<span class="kn">import</span> <span class="nn">timeit</span>
<span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o"><</span> <span class="mi">2</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="n">fib</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">prev</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
<span class="n">prev</span><span class="p">,</span> <span class="n">fib</span> <span class="o">=</span> <span class="n">fib</span><span class="p">,</span> <span class="n">fib</span> <span class="o">+</span> <span class="n">prev</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">executor</span> <span class="o">=</span> <span class="n">concurrent</span><span class="o">.</span><span class="n">futures</span><span class="o">.</span><span class="n">ProcessPoolExecutor</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">tasks</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_in_executor</span><span class="p">(</span><span class="n">executor</span><span class="p">,</span> <span class="n">fib</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10000</span><span class="p">,</span> <span class="mi">11000</span><span class="p">)</span>
<span class="p">]</span>
<span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait</span><span class="p">(</span><span class="n">tasks</span><span class="p">)</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">elapsed</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Async took </span><span class="si">%0.2f</span><span class="s1">s'</span> <span class="o">%</span> <span class="n">elapsed</span><span class="p">)</span>
</pre></div>
</td></tr></table><ul class="simple">
<li>Here the fib function is blocking. It is not a coroutine thus we need
some way to run the function in a separate process.</li>
<li>To do so we can use a process pool from the concurrent futures
library.</li>
<li>We generate a list of tasks each running fib in the process pool.</li>
</ul>
</div>
<div class="section" id="first-completed">
<h3>First Completed</h3>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 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</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">timeit</span>
<span class="kn">from</span> <span class="nn">concurrent.futures</span> <span class="kn">import</span> <span class="n">FIRST_COMPLETED</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">sleep</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Start sleep'</span><span class="p">)</span>
<span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Stop sleep'</span><span class="p">)</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">tasks</span> <span class="o">=</span> <span class="p">[</span><span class="n">sleep</span><span class="p">(</span><span class="o">.</span><span class="mi">8</span><span class="p">),</span> <span class="n">sleep</span><span class="p">(</span><span class="o">.</span><span class="mi">9</span><span class="p">)]</span>
<span class="n">done</span><span class="p">,</span> <span class="n">pending</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait</span><span class="p">(</span>
<span class="n">tasks</span><span class="p">,</span>
<span class="n">return_when</span><span class="o">=</span><span class="n">FIRST_COMPLETED</span>
<span class="p">)</span>
<span class="k">for</span> <span class="n">future</span> <span class="ow">in</span> <span class="n">pending</span><span class="p">:</span>
<span class="n">future</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">elapsed</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'First took </span><span class="si">%0.2f</span><span class="s1">s'</span> <span class="o">%</span> <span class="n">elapsed</span><span class="p">)</span>
</pre></div>
</td></tr></table> <div class="highlight"><pre><span></span>Start sleep
Start sleep
Stop sleep
Firt took <span class="m">0</span>.80s
</pre></div>
<ul class="simple">
<li>Call asyncio.wait with FIRST_COMPLETED flag to stop after first task
completes.</li>
<li>Any tasks/futures that have not completed should be canceled.</li>
<li>Execution time is same as the shortest sleep call.</li>
</ul>
</div>
</div>
<div class="section" id="how-does-curio-stack-up-against-asyncio">
<h2>How does Curio stack up against asyncio?</h2>
<p>As you can see Curio syntax is closer to threading than asycnio.
However, it is also single threaded just like asyncio.</p>
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 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</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">curio</span>
<span class="kn">import</span> <span class="nn">timeit</span>
<span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o"><</span> <span class="mi">2</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="n">fib</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">prev</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
<span class="n">prev</span><span class="p">,</span> <span class="n">fib</span> <span class="o">=</span> <span class="n">fib</span><span class="p">,</span> <span class="n">fib</span> <span class="o">+</span> <span class="n">prev</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">tasks</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10000</span><span class="p">,</span> <span class="mi">11000</span><span class="p">):</span>
<span class="n">task</span> <span class="o">=</span> <span class="k">await</span> <span class="n">curio</span><span class="o">.</span><span class="n">spawn</span><span class="p">(</span><span class="n">curio</span><span class="o">.</span><span class="n">run_in_process</span><span class="p">,</span> <span class="n">fib</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
<span class="n">tasks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
<span class="k">for</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">tasks</span><span class="p">:</span>
<span class="k">await</span> <span class="n">task</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
<span class="n">start_time</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">curio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">)</span>
<span class="n">elapsed</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Curio took </span><span class="si">%0.2f</span><span class="s1">s'</span> <span class="o">%</span> <span class="n">elapsed</span><span class="p">)</span>
</pre></div>
</td></tr></table> <div class="highlight"><pre><span></span>Curio took <span class="m">0</span>.46s
</pre></div>
<p>Slightly more efficient than asyncio. Not surprising since Curio is a
leaner api and a bit more lightweight.</p>
</div>
</section>
<br><br><br>
<footer>
<div class="adjust-width">
<div id="author-block" class="w3-light-grey w3-border">
<div id="author-info">
<a href="https://smarlowucf.github.io"><img class="avatar" src="https://i.stack.imgur.com/L2czk.jpg?s=328&g=1" onerror="this.src='theme/images/avatar.png'" alt="Avatar"></a>
<div style="margin-left: 20px;">
<a href="https://smarlowucf.github.io"><span id="author-name" class="w3-hover-text-dark-grey">Sean Marlow</span></a>
<p id="author-story">Hi! I'm Sean - A Python developer.</p>
</div>
</div>
</div>
</div>
<br><br><br>
</footer>
</div>
</article>
<footer id="footer">
<div id="footer-copyright" class="w3-center w3-small w3-text-grey w3-padding-48">
<span>
©
Sean Marlow
| <a href="https://smarlowucf.github.io/feeds/all.atom.xml">Atom feed <i class="fa fa-rss" aria-hidden="true"></i></a> </span>
</div>
</footer>
</body>
</html>