summaryrefslogtreecommitdiff
path: root/docs/examples/userguide/numpy_tutorial/numpy_and_cython.ipynb
blob: e2fc587734358f0825c9a7b0bf56d810e2e516ef (plain)
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Cython for NumPy users"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To follow the tutorial, see https://cython.readthedocs.io/en/latest/src/userguide/numpy_tutorial.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Disabling color, you really want to install colorlog.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.29a0\n"
     ]
    }
   ],
   "source": [
    "from __future__ import print_function\n",
    "%load_ext cython\n",
    "import Cython\n",
    "print(Cython.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "array_1 = np.random.uniform(0, 1000, size=(3000, 2000)).astype(np.intc)\n",
    "array_2 = np.random.uniform(0, 1000, size=(3000, 2000)).astype(np.intc)\n",
    "a = 4\n",
    "b = 3\n",
    "c = 9"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The first Cython program"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Numpy version"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_np(array_1, array_2, a, b, c):\n",
    "    return np.clip(array_1, 2, 10) * a + array_2 * b + c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "103 ms ± 2.68 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
     ]
    }
   ],
   "source": [
    "timeit_result = %timeit -o compute_np(array_1, array_2, a, b, c)\n",
    "np_time = timeit_result.average"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "np_result = compute_np(array_1, array_2, a, b, c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Pure Python version"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def clip(a, min_value, max_value):\n",
    "    return min(max(a, min_value), max_value)\n",
    "\n",
    "\n",
    "def compute(array_1, array_2, a, b, c):\n",
    "    \"\"\"\n",
    "    This function must implement the formula\n",
    "    np.clip(array_1, 2, 10) * a + array_2 * b + c\n",
    "\n",
    "    array_1 and array_2 are 2D.\n",
    "    \"\"\"\n",
    "    x_max = array_1.shape[0]\n",
    "    y_max = array_1.shape[1]\n",
    "    \n",
    "    assert array_1.shape == array_2.shape\n",
    "\n",
    "    result = np.zeros((x_max, y_max), dtype=array_1.dtype)\n",
    "\n",
    "    for x in range(x_max):\n",
    "        for y in range(y_max):\n",
    "\n",
    "            tmp = clip(array_1[x, y], 2, 10)\n",
    "            tmp = tmp * a + array_2[x, y] * b\n",
    "            result[x, y] = tmp + c\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert np.all(compute(array_1, array_2, a, b, c) == np_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1min 10s ± 844 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
     ]
    }
   ],
   "source": [
    "timeit_result = %timeit -o compute(array_1, array_2, a, b, c)\n",
    "py_time = timeit_result.average"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### We make a function to be able to easily compare timings with the NumPy version and the pure Python version."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compare_time(current, reference, name):\n",
    "    ratio = reference/current\n",
    "    if ratio > 1:\n",
    "        word = \"faster\"\n",
    "    else:\n",
    "        ratio = 1 / ratio \n",
    "        word = \"slower\"\n",
    "        \n",
    "    print(\"We are\", \"{0:.1f}\".format(ratio), \"times\", word, \"than the\", name, \"version.\")\n",
    "\n",
    "def print_report(compute_function):\n",
    "    assert np.all(compute_function(array_1, array_2, a, b, c) == np_result)\n",
    "    timeit_result = %timeit -o compute_function(array_1, array_2, a, b, c)\n",
    "    run_time = timeit_result.average\n",
    "    compare_time(run_time, py_time, \"pure Python\")\n",
    "    compare_time(run_time, np_time, \"NumPy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Pure Python version compiled with Cython:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%%cython -a\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "def clip(a, min_value, max_value):\n",
    "    return min(max(a, min_value), max_value)\n",
    "\n",
    "\n",
    "def compute(array_1, array_2, a, b, c):\n",
    "    \"\"\"\n",
    "    This function must implement the formula\n",
    "    np.clip(array_1, 2, 10) * a + array_2 * b + c\n",
    "\n",
    "    array_1 and array_2 are 2D.\n",
    "    \"\"\"\n",
    "    x_max = array_1.shape[0]\n",
    "    y_max = array_1.shape[1]\n",
    "    \n",
    "    assert array_1.shape == array_2.shape\n",
    "\n",
    "    result = np.zeros((x_max, y_max), dtype=array_1.dtype)\n",
    "\n",
    "    for x in range(x_max):\n",
    "        for y in range(y_max):\n",
    "\n",
    "            tmp = clip(array_1[x, y], 2, 10)\n",
    "            tmp = tmp * a + array_2[x, y] * b\n",
    "            result[x, y] = tmp + c\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "56.5 s ± 587 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n",
      "We are 1.2 times faster than the pure Python version.\n",
      "We are 546.0 times slower than the NumPy version.\n"
     ]
    }
   ],
   "source": [
    "print_report(compute)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Adding types:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%%cython -a\n",
    "import numpy as np\n",
    "\n",
    "# We now need to fix a datatype for our arrays. I've used the variable\n",
    "# DTYPE for this, which is assigned to the usual NumPy runtime\n",
    "# type info object.\n",
    "DTYPE = np.intc\n",
    "\n",
    "# cdef means here that this function is a plain C function (so faster).\n",
    "# To get all the benefits, we type the arguments and the return value as int.\n",
    "cdef int clip(int a, int min_value, int max_value):\n",
    "    return min(max(a, min_value), max_value)\n",
    "\n",
    "\n",
    "def compute(array_1, array_2, int a, int b, int c):\n",
    "    \n",
    "    # The \"cdef\" keyword is also used within functions to type variables. It\n",
    "    # can only be used at the top indentation level (there are non-trivial\n",
    "    # problems with allowing them in other places, though we'd love to see\n",
    "    # good and thought out proposals for it).\n",
    "    cdef Py_ssize_t x_max = array_1.shape[0]\n",
    "    cdef Py_ssize_t y_max = array_1.shape[1]\n",
    "    \n",
    "    assert array_1.shape == array_2.shape\n",
    "    assert array_1.dtype == DTYPE\n",
    "    assert array_2.dtype == DTYPE\n",
    "\n",
    "    result = np.zeros((x_max, y_max), dtype=DTYPE)\n",
    "    \n",
    "    # It is very important to type ALL your variables. You do not get any\n",
    "    # warnings if not, only much slower code (they are implicitly typed as\n",
    "    # Python objects).\n",
    "    # For the \"tmp\" variable, we want to use the same data type as is\n",
    "    # stored in the array, so we use int because it correspond to np.intc.\n",
    "    # NB! An important side-effect of this is that if \"tmp\" overflows its\n",
    "    # datatype size, it will simply wrap around like in C, rather than raise\n",
    "    # an error like in Python.\n",
    "\n",
    "    cdef int tmp\n",
    "    cdef Py_ssize_t x, y\n",
    "\n",
    "    for x in range(x_max):\n",
    "        for y in range(y_max):\n",
    "\n",
    "            tmp = clip(array_1[x, y], 2, 10)\n",
    "            tmp = tmp * a + array_2[x, y] * b\n",
    "            result[x, y] = tmp + c\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "26.5 s ± 422 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n",
      "We are 2.7 times faster than the pure Python version.\n",
      "We are 256.2 times slower than the NumPy version.\n"
     ]
    }
   ],
   "source": [
    "print_report(compute)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Efficient indexing with memoryviews:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%%cython -a\n",
    "import numpy as np\n",
    "\n",
    "DTYPE = np.intc\n",
    "\n",
    "\n",
    "cdef int clip(int a, int min_value, int max_value):\n",
    "    return min(max(a, min_value), max_value)\n",
    "\n",
    "\n",
    "def compute(int[:, :] array_1, int[:, :] array_2, int a, int b, int c):\n",
    "     \n",
    "    cdef Py_ssize_t x_max = array_1.shape[0]\n",
    "    cdef Py_ssize_t y_max = array_1.shape[1]\n",
    "    \n",
    "    assert tuple(array_1.shape) == tuple(array_2.shape)\n",
    "\n",
    "    result = np.zeros((x_max, y_max), dtype=DTYPE)\n",
    "    cdef int[:, :] result_view = result\n",
    "\n",
    "    cdef int tmp\n",
    "    cdef Py_ssize_t x, y\n",
    "\n",
    "    for x in range(x_max):\n",
    "        for y in range(y_max):\n",
    "\n",
    "            tmp = clip(array_1[x, y], 2, 10)\n",
    "            tmp = tmp * a + array_2[x, y] * b\n",
    "            result_view[x, y] = tmp + c\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22.9 ms ± 197 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n",
      "We are 3081.0 times faster than the pure Python version.\n",
      "We are 4.5 times faster than the NumPy version.\n"
     ]
    }
   ],
   "source": [
    "print_report(compute)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Tuning indexing further:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%%cython -a\n",
    "import numpy as np\n",
    "cimport cython\n",
    "\n",
    "DTYPE = np.intc\n",
    "\n",
    "\n",
    "cdef int clip(int a, int min_value, int max_value):\n",
    "    return min(max(a, min_value), max_value)\n",
    "\n",
    "@cython.boundscheck(False)\n",
    "@cython.wraparound(False)\n",
    "def compute(int[:, :] array_1, int[:, :] array_2, int a, int b, int c):\n",
    "     \n",
    "    cdef Py_ssize_t x_max = array_1.shape[0]\n",
    "    cdef Py_ssize_t y_max = array_1.shape[1]\n",
    "    \n",
    "    assert tuple(array_1.shape) == tuple(array_2.shape)\n",
    "\n",
    "    result = np.zeros((x_max, y_max), dtype=DTYPE)\n",
    "    cdef int[:, :] result_view = result\n",
    "\n",
    "    cdef int tmp\n",
    "    cdef Py_ssize_t x, y\n",
    "\n",
    "    for x in range(x_max):\n",
    "        for y in range(y_max):\n",
    "\n",
    "            tmp = clip(array_1[x, y], 2, 10)\n",
    "            tmp = tmp * a + array_2[x, y] * b\n",
    "            result_view[x, y] = tmp + c\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "16.8 ms ± 25.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
      "We are 4200.7 times faster than the pure Python version.\n",
      "We are 6.2 times faster than the NumPy version.\n"
     ]
    }
   ],
   "source": [
    "print_report(compute)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Declaring the NumPy arrays as contiguous."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%cython\n",
    "import numpy as np\n",
    "cimport cython\n",
    "\n",
    "DTYPE = np.intc\n",
    "\n",
    "\n",
    "cdef int clip(int a, int min_value, int max_value):\n",
    "    return min(max(a, min_value), max_value)\n",
    "\n",
    "\n",
    "@cython.boundscheck(False)\n",
    "@cython.wraparound(False)\n",
    "def compute(int[:, ::1] array_1, int[:, ::1] array_2, int a, int b, int c):\n",
    "     \n",
    "    cdef Py_ssize_t x_max = array_1.shape[0]\n",
    "    cdef Py_ssize_t y_max = array_1.shape[1]\n",
    "    \n",
    "    assert tuple(array_1.shape) == tuple(array_2.shape)\n",
    "\n",
    "    result = np.zeros((x_max, y_max), dtype=DTYPE)\n",
    "    cdef int[:, ::1] result_view = result\n",
    "\n",
    "    cdef int tmp\n",
    "    cdef Py_ssize_t x, y\n",
    "\n",
    "    for x in range(x_max):\n",
    "        for y in range(y_max):\n",
    "\n",
    "            tmp = clip(array_1[x, y], 2, 10)\n",
    "            tmp = tmp * a + array_2[x, y] * b\n",
    "            result_view[x, y] = tmp + c\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11.1 ms ± 30.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
      "We are 6350.9 times faster than the pure Python version.\n",
      "We are 9.3 times faster than the NumPy version.\n"
     ]
    }
   ],
   "source": [
    "print_report(compute)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Making the function cleaner"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%cython -a\n",
    "# cython: infer_types=True\n",
    "import numpy as np\n",
    "cimport cython\n",
    "\n",
    "DTYPE = np.intc\n",
    "\n",
    "\n",
    "cdef int clip(int a, int min_value, int max_value):\n",
    "    return min(max(a, min_value), max_value)\n",
    "\n",
    "\n",
    "@cython.boundscheck(False)\n",
    "@cython.wraparound(False)\n",
    "def compute(int[:, ::1] array_1, int[:, ::1] array_2, int a, int b, int c):\n",
    "     \n",
    "    x_max = array_1.shape[0]\n",
    "    y_max = array_1.shape[1]\n",
    "    \n",
    "    assert tuple(array_1.shape) == tuple(array_2.shape)\n",
    "\n",
    "    result = np.zeros((x_max, y_max), dtype=DTYPE)\n",
    "    cdef int[:, ::1] result_view = result\n",
    "\n",
    "    cdef int tmp\n",
    "    cdef Py_ssize_t x, y\n",
    "\n",
    "    for x in range(x_max):\n",
    "        for y in range(y_max):\n",
    "\n",
    "            tmp = clip(array_1[x, y], 2, 10)\n",
    "            tmp = tmp * a + array_2[x, y] * b\n",
    "            result_view[x, y] = tmp + c\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11.5 ms ± 261 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
      "We are 6131.2 times faster than the pure Python version.\n",
      "We are 9.0 times faster than the NumPy version.\n"
     ]
    }
   ],
   "source": [
    "print_report(compute)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### More generic code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%%cython\n",
    "# cython: infer_types=True\n",
    "import numpy as np\n",
    "cimport cython\n",
    "\n",
    "ctypedef fused my_type:\n",
    "    int\n",
    "    double\n",
    "    long long\n",
    "\n",
    "\n",
    "cdef my_type clip(my_type a, my_type min_value, my_type max_value):\n",
    "    return min(max(a, min_value), max_value)\n",
    "\n",
    "\n",
    "@cython.boundscheck(False)\n",
    "@cython.wraparound(False)\n",
    "def compute(my_type[:, ::1] array_1, my_type[:, ::1] array_2, my_type a, my_type b, my_type c):\n",
    "     \n",
    "    x_max = array_1.shape[0]\n",
    "    y_max = array_1.shape[1]\n",
    "    \n",
    "    assert tuple(array_1.shape) == tuple(array_2.shape)\n",
    "    \n",
    "    if my_type is int:\n",
    "        dtype = np.intc\n",
    "    elif my_type is double:\n",
    "        dtype = np.double\n",
    "    elif my_type is cython.longlong:\n",
    "        dtype = np.double\n",
    "        \n",
    "    result = np.zeros((x_max, y_max), dtype=dtype)\n",
    "    cdef my_type[:, ::1] result_view = result\n",
    "\n",
    "    cdef my_type tmp\n",
    "    cdef Py_ssize_t x, y\n",
    "\n",
    "    for x in range(x_max):\n",
    "        for y in range(y_max):\n",
    "\n",
    "            tmp = clip(array_1[x, y], 2, 10)\n",
    "            tmp = tmp * a + array_2[x, y] * b\n",
    "            result_view[x, y] = tmp + c\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "arr_1_float = array_1.astype(np.float64)\n",
    "arr_2_float = array_2.astype(np.float64)\n",
    "\n",
    "float_cython_result = compute(arr_1_float, arr_2_float, a, b, c)\n",
    "float_numpy_result = compute_np(arr_1_float, arr_2_float, a, b, c)\n",
    "\n",
    "assert np.all(float_cython_result == float_numpy_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11.5 ms ± 258 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
      "We are 6153.1 times faster than the pure Python version.\n",
      "We are 9.0 times faster than the NumPy version.\n"
     ]
    }
   ],
   "source": [
    "print_report(compute)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Using multiple threads"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%%cython --force\n",
    "# distutils: extra_compile_args=-fopenmp\n",
    "# distutils: extra_link_args=-fopenmp\n",
    "import numpy as np\n",
    "cimport cython\n",
    "from cython.parallel import prange\n",
    "\n",
    "ctypedef fused my_type:\n",
    "    int\n",
    "    double\n",
    "    long long\n",
    "\n",
    "\n",
    "# We declare our plain c function nogil\n",
    "cdef my_type clip(my_type a, my_type min_value, my_type max_value) nogil:\n",
    "    return min(max(a, min_value), max_value)\n",
    "\n",
    "\n",
    "@cython.boundscheck(False)\n",
    "@cython.wraparound(False)\n",
    "def compute(my_type[:, ::1] array_1, my_type[:, ::1] array_2, my_type a, my_type b, my_type c):\n",
    "     \n",
    "    cdef Py_ssize_t x_max = array_1.shape[0]\n",
    "    cdef Py_ssize_t y_max = array_1.shape[1]\n",
    "    \n",
    "    assert tuple(array_1.shape) == tuple(array_2.shape)\n",
    "    \n",
    "    if my_type is int:\n",
    "        dtype = np.intc\n",
    "    elif my_type is double:\n",
    "        dtype = np.double\n",
    "    elif my_type is cython.longlong:\n",
    "        dtype = np.longlong\n",
    "        \n",
    "    result = np.zeros((x_max, y_max), dtype=dtype)\n",
    "    cdef my_type[:, ::1] result_view = result\n",
    "\n",
    "    cdef my_type tmp\n",
    "    cdef Py_ssize_t x, y\n",
    "\n",
    "    # We use prange here.\n",
    "    for x in prange(x_max, nogil=True):\n",
    "        for y in range(y_max):\n",
    "\n",
    "            tmp = clip(array_1[x, y], 2, 10)\n",
    "            tmp = tmp * a + array_2[x, y] * b\n",
    "            result_view[x, y] = tmp + c\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9.33 ms ± 412 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
      "We are 7559.0 times faster than the pure Python version.\n",
      "We are 11.1 times faster than the NumPy version.\n"
     ]
    }
   ],
   "source": [
    "print_report(compute)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}