8000 Merge pull request #2979 from jdb8/cpu-sched-getaffinity · pre-commit/pre-commit@ac42dc5 · GitHub
[go: up one dir, main page]

Skip to content

Commit ac42dc5

Browse files
authored
Merge pull request #2979 from jdb8/cpu-sched-getaffinity
Use os.sched_getaffinity for cpu counts when available
2 parents 9ebda91 + ea8244b commit ac42dc5

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

pre_commit/xargs.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@
2424

2525

2626
def cpu_count() -> int:
27+
try:
28+
# On systems that support it, this will return a more accurate count of
29+
# usable CPUs for the current process, which will take into account
30+
# cgroup limits
31+
return len(os.sched_getaffinity(0))
32+
except AttributeError:
33+
pass
34+
2735
try:
2836
return multiprocessing.cpu_count()
2937
except NotImplementedError:

tests/lang_base_test.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,19 @@ def fake_expanduser(pth):
3030
yield
3131

3232

33+
@pytest.fixture
34+
def no_sched_getaffinity():
35+
# Simulates an OS without os.sched_getaffinity available (mac/windows)
36+
# https://docs.python.org/3/library/os.html#interface-to-the-scheduler
37+
with mock.patch.object(
38+
os,
39+
'sched_getaffinity',
40+
create=True,
41+
side_effect=AttributeError,
42+
):
43+
yield
44+
45+
3346
def test_exe_exists_does_not_exist(find_exe_mck, homedir_mck):
3447
find_exe_mck.return_value = None 8000
3548
assert lang_base.exe_exists('ruby') is False
@@ -116,7 +129,17 @@ def test_no_env_noop(tmp_path):
116129
assert before == inside == after
117130

118131

119-
def test_target_concurrency_normal():
132+
def test_target_concurrency_sched_getaffinity(no_sched_getaffinity):
133+
with mock.patch.object(
134+
os,
135+
'sched_getaffinity',
136+
return_value=set(range(345)),
137+
):
138+
with mock.patch.dict(os.environ, clear=True):
139+
assert lang_base.target_concurrency() == 345
140+
141+
142+
def test_target_concurrency_without_sched_getaffinity(no_sched_getaffinity):
120143
with mock.patch.object(multiprocessing, 'cpu_count', return_value=123):
121144
with mock.patch.dict(os.environ, {}, clear=True):
122145
assert lang_base.target_concurrency() == 123
@@ -134,7 +157,7 @@ def test_target_concurrency_on_travis():
134157
assert lang_base.target_concurrency() == 2
135158

136159

137-
def test_target_concurrency_cpu_count_not_implemented():
160+
def test_target_concurrency_cpu_count_not_implemented(no_sched_getaffinity):
138161
with mock.patch.object(
139162
multiprocessing, 'cpu_count', side_effect=NotImplementedError,
140163
):

0 commit comments

Comments
 (0)
0