numthreads 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ Copyright 2023, Bas Nijholt
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.1
2
+ Name: numthreads
3
+ Version: 0.1.0
4
+ Summary: Set the number of threads for OpenBLAS, MKL, OMP, NumExpr, and Accelerate.
5
+ Author-email: Bas Nijholt <bas@nijho.lt>
6
+ Project-URL: Homepage, https://github.com/basnijholt/numthreads
7
+ Requires-Python: >=3.7
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Provides-Extra: docs
11
+ Requires-Dist: myst-parser ; extra == 'docs'
12
+ Requires-Dist: sphinx ; extra == 'docs'
13
+ Requires-Dist: furo ; extra == 'docs'
14
+ Requires-Dist: emoji ; extra == 'docs'
15
+ Requires-Dist: sphinx-autodoc-typehints ; extra == 'docs'
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest ; extra == 'test'
18
+ Requires-Dist: pre-commit ; extra == 'test'
19
+ Requires-Dist: coverage ; extra == 'test'
20
+ Requires-Dist: pytest-cov ; extra == 'test'
21
+ Requires-Dist: pytest-mock ; extra == 'test'
22
+
23
+ [![PyPI](https://img.shields.io/pypi/v/numthreads.svg)](https://pypi.python.org/pypi/numthreads)
24
+ [![Build Status](https://github.com/basnijholt/numthreads/actions/workflows/pytest.yml/badge.svg)](https://github.com/basnijholt/numthreads/actions/workflows/pytest.yml)
25
+ [![CodeCov](https://codecov.io/gh/basnijholt/numthreads/branch/main/graph/badge.svg)](https://codecov.io/gh/basnijholt/numthreads)
26
+ [![GitHub Repo stars](https://img.shields.io/github/stars/basnijholt/numthreads)](https://github.com/basnijholt/numthreads)
27
+ [![Documentation](https://readthedocs.org/projects/numthreads/badge/?version=latest)](https://numthreads.readthedocs.io/)
28
+
29
+ `numthreads` is a concise, easy-to-use tool designed to set the number of threads for various computing libraries including OpenBLAS, Intel's Math Kernel Library (MKL), OpenMP, NumExpr, and Accelerate.
30
+ This Python-based utility aids in optimizing the performance of numerical and scientific computing applications by allowing users to efficiently control the threading behavior of these key libraries.
31
+
32
+ <!-- toc-start -->
33
+
34
+ ## :books: Table of Contents
35
+
36
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
37
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
38
+
39
+ - [:sparkles: Features](#sparkles-features)
40
+ - [:package: Installation](#package-installation)
41
+ - [:rocket: Quick Start](#rocket-quick-start)
42
+ - [Unix-like Systems (Linux, macOS, WSL)](#unix-like-systems-linux-macos-wsl)
43
+ - [Windows (PowerShell)](#windows-powershell)
44
+ - [Using as a Python Module](#using-as-a-python-module)
45
+ - [:question: Getting Help](#question-getting-help)
46
+
47
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
48
+
49
+ <!-- toc-end -->
50
+
51
+ ## :sparkles: Features
52
+
53
+ - Simple and straightforward command-line interface.
54
+ - Sets thread count for OpenBLAS, MKL, OpenMP, NumExpr, and Accelerate.
55
+ - Context manager support for temporary thread setting in Python code.
56
+ - Cross-platform compatibility (Linux, macOS, Windows).
57
+
58
+ ## :package: Installation
59
+
60
+ To install `numthreads`, run the following command:
61
+
62
+ ```bash
63
+ pip install "numthreads"
64
+ ```
65
+
66
+ ## :rocket: Quick Start
67
+
68
+ After installing `numthreads`, you can easily set the number of threads used by supported libraries via the command line. For example, to set the number of threads to 4, run:
69
+
70
+ ```bash
71
+ numthreads 4
72
+ ```
73
+
74
+ ### Unix-like Systems (Linux, macOS, WSL)
75
+
76
+ To apply the settings in your shell:
77
+
78
+ ```bash
79
+ eval $(numthreads <number_of_threads>)
80
+ ```
81
+
82
+ ### Windows (PowerShell)
83
+
84
+ In PowerShell, use:
85
+
86
+ ```powershell
87
+ Invoke-Expression $(numthreads <number_of_threads>)
88
+ ```
89
+
90
+ ### Using as a Python Module
91
+
92
+ You can also use `numthreads` as a Python module:
93
+
94
+ ```python
95
+ from numthreads import set_num_threads
96
+
97
+ set_num_threads(4)
98
+ ```
99
+
100
+ or
101
+
102
+ ```python
103
+ from numthreads import num_threads
104
+
105
+ with num_threads(4):
106
+ # Your code here will run with the specified number of threads
107
+ pass
108
+ ```
109
+
110
+ ## :question: Getting Help
111
+
112
+ For more information, or to report issues, please visit [numthreads GitHub repository](https://github.com/basnijholt/numthreads).
@@ -0,0 +1,7 @@
1
+ numthreads.py,sha256=F--rGKtJS7QDF39ljh4vqj7Az1m8nnVFPTSzuBDirKo,3708
2
+ numthreads-0.1.0.dist-info/LICENSE,sha256=FIu1oQpGHdOwvpL_33f0lGehX7GDxBteS3S-tYCfv1M,1060
3
+ numthreads-0.1.0.dist-info/METADATA,sha256=vFKytmdLcBlTrALLrl8wLUer-H9PYKk8vDDBTiCr0Ts,3869
4
+ numthreads-0.1.0.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
5
+ numthreads-0.1.0.dist-info/entry_points.txt,sha256=FBwwjhgpoDkzhi2H40GdVrDLvZ2a7p4D0CbDdu8raYg,47
6
+ numthreads-0.1.0.dist-info/top_level.txt,sha256=RC5p79FQlH2JmROjrbJaYkYKt3hxYrE9HT97H7_XVak,11
7
+ numthreads-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ numthreads = numthreads:main
@@ -0,0 +1 @@
1
+ numthreads
numthreads.py ADDED
@@ -0,0 +1,123 @@
1
+ """numthreads: Set the number of threads for OpenBLAS, MKL, OMP, NumExpr, and Accelerate.""" # noqa: E501
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import contextlib
6
+ import ctypes
7
+ import os
8
+ import platform
9
+ import sys
10
+ from typing import TYPE_CHECKING
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Generator
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ THREAD_CONTROL_ENV_VARS = [
18
+ "OPENBLAS_NUM_THREADS", # OpenBLAS
19
+ "MKL_NUM_THREADS", # MKL
20
+ "OMP_NUM_THREADS", # OMP
21
+ "NUMEXPR_NUM_THREADS", # NumExpr
22
+ "VECLIB_MAXIMUM_THREADS", # Accelerate
23
+ ]
24
+
25
+
26
+ def set_num_threads(n: int = 1) -> None:
27
+ """Set the number of threads for OpenBLAS, MKL, OMP, NumExpr, and Accelerate."""
28
+ for var in THREAD_CONTROL_ENV_VARS:
29
+ os.environ[var] = str(n)
30
+
31
+
32
+ @contextlib.contextmanager
33
+ def num_threads(n: int = 1) -> Generator[None, None, None]:
34
+ """Context manager to set and then restore thread number settings."""
35
+ original_settings = {var: os.environ.get(var) for var in THREAD_CONTROL_ENV_VARS}
36
+
37
+ set_num_threads(n)
38
+
39
+ try:
40
+ yield
41
+ finally:
42
+ for var, value in original_settings.items():
43
+ if value is None: # pragma: no cover
44
+ os.environ.pop(var, None)
45
+ else:
46
+ os.environ[var] = value
47
+
48
+
49
+ def _load_omp_library() -> ctypes.CDLL:
50
+ """Loads the OpenMP library based on the operating system."""
51
+ system = platform.system()
52
+
53
+ if system == "Darwin": # pragma: no cover
54
+ lib_name = "libomp.dylib"
55
+ elif system == "Linux": # pragma: no cover
56
+ lib_name = "libgomp.so.1"
57
+ elif system == "Windows": # pragma: no cover
58
+ lib_name = "libiomp5md.dll"
59
+ else: # pragma: no cover
60
+ msg = f"Unsupported operating system: {system}"
61
+ raise NotImplementedError(msg)
62
+
63
+ try:
64
+ return ctypes.CDLL(lib_name)
65
+ except OSError as e: # pragma: no cover
66
+ msg = f"Error loading {lib_name}. Make sure OpenMP is installed."
67
+ raise OSError(msg) from e
68
+
69
+
70
+ def omp_set_num_threads(num_threads: int) -> None:
71
+ """Sets the number of threads to be used by OpenMP parallel regions.
72
+
73
+ Parameters
74
+ ----------
75
+ num_threads
76
+ Number of threads to set.
77
+ """
78
+ omp_lib = _load_omp_library()
79
+ omp_lib.omp_set_num_threads(num_threads)
80
+
81
+
82
+ def omp_get_num_threads() -> int:
83
+ """Returns the number of threads in the current OpenMP parallel region."""
84
+ omp_lib = _load_omp_library()
85
+ omp_lib.omp_get_num_threads.restype = ctypes.c_int
86
+ return omp_lib.omp_get_num_threads()
87
+
88
+
89
+ def main() -> None: # pragma: no cover
90
+ """Command-line interface."""
91
+ description = (
92
+ "Set the number of threads for OpenBLAS, MKL, OMP, NumExpr, and Accelerate."
93
+ " Usage: Run `numthreads <number>` to print the export commands."
94
+ " On Unix-like systems (Linux, macOS, WSL), use `eval $(numthreads <number>)`"
95
+ " in your shell to apply these settings."
96
+ " On Windows, in PowerShell, use `Invoke-Expression $(numthreads <number>)`."
97
+ )
98
+ parser = argparse.ArgumentParser(
99
+ description=description,
100
+ )
101
+ parser.add_argument(
102
+ "n",
103
+ type=int,
104
+ help="Number of threads to set.",
105
+ )
106
+ args = parser.parse_args(args=None if sys.argv[1:] else ["--help"])
107
+
108
+ n = args.n
109
+ system = platform.system()
110
+ if system == "Windows":
111
+ export_commands = " & ".join(
112
+ f"$env:{var}={n}" for var in THREAD_CONTROL_ENV_VARS
113
+ )
114
+ print(f'powershell.exe -Command "{export_commands}"')
115
+ else:
116
+ export_commands = " ; ".join(
117
+ f"export {var}={n}" for var in THREAD_CONTROL_ENV_VARS
118
+ )
119
+ print(export_commands)
120
+
121
+
122
+ if __name__ == "__main__":
123
+ main()