npthreads.py 2.29 KB
Newer Older
Carl Poelking's avatar
Carl Poelking committed
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
import ctypes
from ctypes.util import find_library

# TAKEN FROM
# http://stackoverflow.com/questions/29559338/set-max-number-of-threads-at-runtime-on-numpy-openblas

# Enforces priority of hand-compiled OpenBLAS library over version in /usr/lib
# that comes from Ubuntu repos
try_paths = ['/opt/OpenBLAS/lib/libopenblas.so',
             '/lib/libopenblas.so',
             '/usr/lib/libopenblas.so.0',
             find_library('openblas')]
openblas_lib = None
for libpath in try_paths:
    try:
        openblas_lib = ctypes.cdll.LoadLibrary(libpath)
        break
    except OSError:
        continue
if openblas_lib is None:
    raise EnvironmentError('Could not locate an OpenBLAS shared library', 2)


def set_num_threads(n):
    """
    Set the current number of threads used by the OpenBLAS server
    """
    openblas_lib.openblas_set_num_threads(int(n))


def num_threads(n):
    """
    Set the OpenBLAS thread context:

        print "Before ", get_num_threads()

        with num_threads(n):
            print "In thread context: ", get_num_threads()

        print "After ", get_num_threads()

    """
    return ThreadContext(n)


class ThreadContext(object):

    def __init__(self, num_threads):
        self._old_num_threads = get_num_threads()
        self.num_threads = num_threads

    def __enter__(self):
        set_num_threads(self.num_threads)

    def __exit__(self, *args):
        set_num_threads(self._old_num_threads)


# these features were added very recently:
# <https://github.com/xianyi/OpenBLAS/commit/65a847cd361d33b4a65c10d13eefb11eb02f04d7>
try:
    openblas_lib.openblas_get_num_threads()
    def get_num_threads():
        """Get the current number of threads used by the OpenBLAS server
        """
        return openblas_lib.openblas_get_num_threads()
except AttributeError:
    def get_num_threads():
        """Dummy function (symbol not present in %s), returns -1.
        """ % openblas_lib._name
        return -1
    pass

try:
    openblas_lib.openblas_get_num_procs()
    def get_num_procs():
        """Get the total number of physical processors
        """
        return openblas_lib.openblas_get_num_procs()
except AttributeError:
    def get_num_procs():
        """Dummy function (symbol not present in %s), returns -1.
        """ % openblas_lib._name
        return -1
    pass