File: pure_parallel.py

package info (click to toggle)
cython 3.0.11%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 19,092 kB
  • sloc: python: 83,539; ansic: 18,831; cpp: 1,402; xml: 1,031; javascript: 511; makefile: 403; sh: 204; sed: 11
file content (60 lines) | stat: -rw-r--r-- 1,114 bytes parent folder | download | duplicates (5)
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
# mode: run
# tag: openmp, pure3.6

import cython
from cython.parallel import prange, parallel


def prange_regression(n: cython.int, data: list):
    """
    >>> prange_regression(10, list(range(1, 4)))
    19
    """
    s: cython.int = 0
    i: cython.int
    d: cython.int[3] = data

    for i in prange(n, num_threads=3, nogil=True):
        s += d[i % 3]
    return s


def prange_with_gil(n: cython.int, x):
    """
    >>> sum(3*i for i in range(10))
    135
    >>> prange_with_gil(10, 3)
    135
    """
    i: cython.int
    s: cython.int = 0

    for i in prange(n, num_threads=3, nogil=True):
        with cython.gil:
            s += x * i

    return s


@cython.cfunc
def use_nogil(x, i: cython.int) -> cython.int:
    cx: cython.int = x
    with cython.nogil:
        return cx * i


def prange_with_gil_call_nogil(n: cython.int, x):
    """
    >>> sum(3*i for i in range(10))
    135
    >>> prange_with_gil(10, 3)
    135
    """
    i: cython.int
    s: cython.int = 0

    for i in prange(n, num_threads=3, nogil=True):
        with cython.gil:
            s += use_nogil(x, i)

    return s