Merged
fix(build_ci): auto-derive job_num from CPU count and cgroup memory #5721
陈晨Add on Aug 27
fix(build_ci): auto-derive job_num from CPU count and cgroup memory #5721
Merged
Merged fromchen_chenn/pyptofix_build_ci_job_numintocann/pyptomaster
Total: 8 files changed+225-27
| @@ -68,9 +68,10 @@ from typing import Any, Dict, List, Optional, Tuple | |||
| 68 | from packaging import requirements | 68 | from packaging import requirements |
| 69 | 69 | ||
| 70 | try: | 70 | try: |
| 71 | - from setup import _find_system_cmake | 71 | + from setup import _find_system_cmake, get_job_num |
| 72 | except ImportError: | 72 | except ImportError: |
| 73 | _find_system_cmake = None | 73 | _find_system_cmake = None |
| 74 | + get_job_num = None | ||
| 74 | 75 | ||
| 75 | 76 | ||
| 76 | class CMakeParam(abc.ABC): | 77 | class CMakeParam(abc.ABC): |
| @@ -473,7 +474,14 @@ class BuildParam(CMakeParam): | |||
| 473 | "If you specify more than one, all targets within the specified range are built.", | 474 | "If you specify more than one, all targets within the specified range are built.", |
| 474 | ) | 475 | ) |
| 475 | parser.add_argument( | 476 | parser.add_argument( |
| 476 | - "-j", "--job_num", nargs="?", type=int, default=-1, help="job num, specific job num of build." | 477 | + "-j", |
| 478 | + "--job_num", | ||
| 479 | + nargs="?", | ||
| 480 | + type=int, | ||
| 481 | + default=-1, | ||
| 482 | + help="job num, specific job num of build. " | ||
| 483 | + "If unset, parallelism is auto-derived from CPU count and available memory " | ||
| 484 | + "(env PYPTO_BUILD_JOB_NUM overrides the default).", | ||
| 477 | ) | 485 | ) |
| 478 | 486 | ||
| 479 | @staticmethod | 487 | @staticmethod |
| @@ -506,7 +514,9 @@ class BuildParam(CMakeParam): | |||
| 506 | def _get_job_num(job_num: Optional[int], generator: Optional[str]) -> Optional[int]: | 514 | def _get_job_num(job_num: Optional[int], generator: Optional[str]) -> Optional[int]: |
| 507 | """获取构建并行任务数 | 515 | """获取构建并行任务数 |
| 508 | 516 | ||
| 509 | - 根据系统 CPU 核数和构建生成器类型确定合适的并行任务数. 如果使用 Ninja 生成器, 则由 Ninja 自动决定并行度. | 517 | + 委托至 cmake/scripts/_job_num 公共模块, 综合考虑 CPU 核数、可用内存(含 cgroup 上限) |
| 518 | + 及 PYPTO_BUILD_JOB_NUM 环境变量确定并行度. Ninja 生成器时由 Ninja 自身决定. | ||
| 519 | + 若公共模块不可用, 则回退到仅基于 CPU 核数的旧逻辑. | ||
| 510 | 520 | ||
| 511 | :param job_num: 用户指定的并行任务数 | 521 | :param job_num: 用户指定的并行任务数 |
| 512 | :type job_num: Optional[int] | 522 | :type job_num: Optional[int] |
| @@ -515,6 +525,9 @@ class BuildParam(CMakeParam): | |||
| 515 | :return: 最终的并行任务数, None 表示由构建工具自动决定 | 525 | :return: 最终的并行任务数, None 表示由构建工具自动决定 |
| 516 | :rtype: Optional[int] | 526 | :rtype: Optional[int] |
| 517 | """ | 527 | """ |
| 528 | + if get_job_num is not None: | ||
| 529 | + return get_job_num(job_num=job_num, generator=generator) | ||
| 530 | + # Fallback: CPU-only calculation (kept for environments where setup.py import fails) | ||
| 518 | def_job_num = min(int(math.ceil(float(multiprocessing.cpu_count()) * 0.9)), 128) # 128 为缺省最大核数 | 531 | def_job_num = min(int(math.ceil(float(multiprocessing.cpu_count()) * 0.9)), 128) # 128 为缺省最大核数 |
| 519 | def_job_num = ( | 532 | def_job_num = ( |
| 520 | None | 533 | None |
| @@ -564,7 +577,7 @@ class BuildParam(CMakeParam): | |||
| 564 | _p = Path(self.clang_install_path, _b) | 577 | _p = Path(self.clang_install_path, _b) |
| 565 | if _p.exists(): | 578 | if _p.exists(): |
| 566 | return True, self._cfg_require(opt=_opt, tv=str(_p)) | 579 | return True, self._cfg_require(opt=_opt, tv=str(_p)) |
| 567 | - logging.error("Clang Toolchain %s does not exist.", _p) | 580 | + logging.error("Clang Toolchain %s not exist.", _p) |
| 568 | return False, "" | 581 | return False, "" |
| 569 | 582 | ||
| 570 | def _gen_clang_cmd() -> Tuple[bool, str]: | 583 | def _gen_clang_cmd() -> Tuple[bool, str]: |
| @@ -1550,7 +1563,7 @@ class BuildCtrl(CMakeParam): | |||
| 1550 | try: | 1563 | try: |
| 1551 | _, duration = self.run_build_cmd(cmd=c, update_env=update_env) | 1564 | _, duration = self.run_build_cmd(cmd=c, update_env=update_env) |
| 1552 | except subprocess.CalledProcessError as e: | 1565 | except subprocess.CalledProcessError as e: |
| 1553 | - logging.error("CMake Build(%s/%s) failed, ERROR CODE: %s", i, len(cmd_list), e.returncode) | 1566 | + logging.info("CMake Build(%s/%s) failed, ERROR CODE: %s", i, len(cmd_list), e.returncode) |
| 1554 | raise e | 1567 | raise e |
| 1555 | logging.info("CMake Build(%s/%s) success, %s", i, len(cmd_list), duration) | 1568 | logging.info("CMake Build(%s/%s) success, %s", i, len(cmd_list), duration) |
| 1556 | 1569 | ||
| @@ -1898,7 +1911,7 @@ class BuildCtrl(CMakeParam): | |||
| 1898 | whl_files = [Path(f) for f in whl_glob] | 1911 | whl_files = [Path(f) for f in whl_glob] |
| 1899 | whl_file = whl_files[0] if whl_files else None | 1912 | whl_file = whl_files[0] if whl_files else None |
| 1900 | if whl_file: | 1913 | if whl_file: |
| 1901 | - logging.info("Successfully found match %s from %s", whl_file, path) | 1914 | + logging.info("Success find match %s from %s", whl_file, path) |
| 1902 | else: | 1915 | else: |
| 1903 | logging.error("Failed to find match %s whl from %s, pattern=%s", name, path, pattern) | 1916 | logging.error("Failed to find match %s whl from %s, pattern=%s", name, path, pattern) |
| 1904 | return whl_file | 1917 | return whl_file |
| @@ -0,0 +1,164 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Shared utility for computing build parallelism (job_num) with memory awareness. | ||
| 12 | + | ||
| 13 | +This module is loaded by-path from both setup.py and build_ci.py (same pattern as | ||
| 14 | +_which_cmake.py) to avoid import-time dependency on an installed pypto package. | ||
| 15 | +""" | ||
| 16 | + | ||
| 17 | +import math | ||
| 18 | +import multiprocessing | ||
| 19 | +import os | ||
| 20 | +from pathlib import Path | ||
| 21 | +from typing import Optional | ||
| 22 | + | ||
| 23 | +# Conservative estimate of peak RSS per cc1plus translation unit. | ||
| 24 | +# Heavy C++ template instantiation (quantization, codegen, etc.) can reach ~2 GiB. | ||
| 25 | +DEFAULT_MEM_PER_JOB_BYTES: int = 2 * 1024 * 1024 * 1024 # 2 GiB | ||
| 26 | + | ||
| 27 | +# Environment variable for explicit override of build parallelism. | ||
| 28 | +ENV_JOB_NUM: str = "PYPTO_BUILD_JOB_NUM" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def _read_cgroup_memory_limit() -> Optional[int]: | ||
| 32 | + """Read the cgroup memory limit in bytes (v2 then v1). | ||
| 33 | + | ||
| 34 | + :return: Memory limit in bytes, or None if unlimited / unavailable. | ||
| 35 | + :rtype: Optional[int] | ||
| 36 | + """ | ||
| 37 | + # cgroup v2: /sys/fs/cgroup/memory.max (value "max" means no limit) | ||
| 38 | + v2_path = Path("/sys/fs/cgroup/memory.max") | ||
| 39 | + if v2_path.exists(): | ||
| 40 | + raw = v2_path.read_text(encoding="utf-8").strip() | ||
| 41 | + if raw == "max": | ||
| 42 | + return None | ||
| 43 | + try: | ||
| 44 | + limit = int(raw) | ||
| 45 | + if limit > 0: | ||
| 46 | + return limit | ||
| 47 | + except ValueError: | ||
| 48 | + pass | ||
| 49 | + | ||
| 50 | + # cgroup v1: /sys/fs/cgroup/memory/memory.limit_in_bytes | ||
| 51 | + v1_path = Path("/sys/fs/cgroup/memory/memory.limit_in_bytes") | ||
| 52 | + if v1_path.exists(): | ||
| 53 | + raw = v1_path.read_text(encoding="utf-8").strip() | ||
| 54 | + try: | ||
| 55 | + limit = int(raw) | ||
| 56 | + # cgroup v1 uses a very large sentinel (e.g. 2^63 - page) for "no limit" | ||
| 57 | + if 0 < limit < 2**62: | ||
| 58 | + return limit | ||
| 59 | + except ValueError: | ||
| 60 | + pass | ||
| 61 | + return None | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def _read_system_memory() -> Optional[int]: | ||
| 65 | + """Read available system memory from /proc/meminfo (Linux only). | ||
| 66 | + | ||
| 67 | + :return: Available memory in bytes, or None if unavailable. | ||
| 68 | + :rtype: Optional[int] | ||
| 69 | + """ | ||
| 70 | + meminfo_path = Path("/proc/meminfo") | ||
| 71 | + if not meminfo_path.exists(): | ||
| 72 | + return None | ||
| 73 | + mem_total = None | ||
| 74 | + for line in meminfo_path.read_text(encoding="utf-8").splitlines(): | ||
| 75 | + if line.startswith("MemAvailable:"): | ||
| 76 | + parts = line.split() | ||
| 77 | + if len(parts) >= 2: | ||
| 78 | + return int(parts[1]) * 1024 # kB -> bytes | ||
| 79 | + if line.startswith("MemTotal:"): | ||
| 80 | + parts = line.split() | ||
| 81 | + if len(parts) >= 2: | ||
| 82 | + mem_total = int(parts[1]) * 1024 # kB -> bytes | ||
| 83 | + return mem_total | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +def _get_available_memory() -> Optional[int]: | ||
| 87 | + """Get available memory in bytes, preferring cgroup limits. | ||
| 88 | + | ||
| 89 | + :return: Available memory in bytes, or None if unavailable. | ||
| 90 | + :rtype: Optional[int] | ||
| 91 | + """ | ||
| 92 | + cgroup_limit = _read_cgroup_memory_limit() | ||
| 93 | + if cgroup_limit: | ||
| 94 | + return cgroup_limit | ||
| 95 | + return _read_system_memory() | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def _parse_env_int(env_var: str) -> Optional[int]: | ||
| 99 | + """Parse a positive integer from an environment variable. | ||
| 100 | + | ||
| 101 | + :param env_var: Environment variable name. | ||
| 102 | + :return: Parsed positive int, or None if unset / invalid. | ||
| 103 | + :rtype: Optional[int] | ||
| 104 | + """ | ||
| 105 | + raw = os.environ.get(env_var) | ||
| 106 | + if not raw: | ||
| 107 | + return None | ||
| 108 | + try: | ||
| 109 | + val = int(raw) | ||
| 110 | + if val > 0: | ||
| 111 | + return val | ||
| 112 | + except ValueError: | ||
| 113 | + pass | ||
| 114 | + return None | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +def get_job_num( | ||
| 118 | + job_num: Optional[int] = None, | ||
| 119 | + generator: Optional[str] = None, | ||
| 120 | + max_cpu_ratio: float = 0.9, | ||
| 121 | + max_cpu: int = 128, | ||
| 122 | + mem_per_job_bytes: int = DEFAULT_MEM_PER_JOB_BYTES, | ||
| 123 | +) -> Optional[int]: | ||
| 124 | + """Compute build parallelism considering CPU count and available memory. | ||
| 125 | + | ||
| 126 | + Priority (highest first): | ||
| 127 | + 1. Explicit job_num from CLI (-j flag), if > 0 | ||
| 128 | + 2. PYPTO_BUILD_JOB_NUM environment variable | ||
| 129 | + 3. min(cpu_based, memory_based, max_cpu) — memory-aware default | ||
| 130 | + 4. None for Ninja generator (let Ninja decide) | ||
| 131 | + | ||
| 132 | + :param job_num: User-specified parallelism from CLI. None or <=0 means "auto". | ||
| 133 | + :type job_num: Optional[int] | ||
| 134 | + :param generator: CMake generator name. Ninja returns None (auto-decide). | ||
| 135 | + :type generator: Optional[str] | ||
| 136 | + :param max_cpu_ratio: Fraction of CPU count to use for the CPU-based default. | ||
| 137 | + :type max_cpu_ratio: float | ||
| 138 | + :param max_cpu: Hard cap on CPU-based parallelism. | ||
| 139 | + :type max_cpu: int | ||
| 140 | + :param mem_per_job_bytes: Estimated peak RSS per compilation unit (bytes). | ||
| 141 | + :type mem_per_job_bytes: int | ||
| 142 | + :return: Job count, or None for Ninja / automatic. | ||
| 143 | + :rtype: Optional[int] | ||
| 144 | + """ | ||
| 145 | + # Ninja decides its own parallelism | ||
| 146 | + if generator and generator.strip().strip('"').lower() in ("ninja",): | ||
| 147 | + return None | ||
| 148 | + | ||
| 149 | + # Priority 1: explicit CLI flag | ||
| 150 | + if job_num and job_num > 0: | ||
| 151 | + return job_num | ||
| 152 | + | ||
| 153 | + # Priority 2: environment variable override | ||
| 154 | + env_val = _parse_env_int(ENV_JOB_NUM) | ||
| 155 | + if env_val: | ||
| 156 | + return env_val | ||
| 157 | + | ||
| 158 | + # Priority 3: memory-aware default | ||
| 159 | + cpu_based = min(int(math.ceil(float(multiprocessing.cpu_count()) * max_cpu_ratio)), max_cpu) | ||
| 160 | + available_mem = _get_available_memory() | ||
| 161 | + if available_mem and available_mem > 0: | ||
| 162 | + mem_based = max(1, available_mem // mem_per_job_bytes) | ||
| 163 | + return min(cpu_based, mem_based) | ||
| 164 | + return cpu_based | ||
| @@ -47,6 +47,12 @@ python3 build_ci.py --clean --no_isolation | |||
| 47 | | `--just_build_whl` | 只构建whl包,不打包进入run安装包。 | | 47 | | `--just_build_whl` | 只构建whl包,不打包进入run安装包。 | |
| 48 | | `--py_abi` | 指定whl包的Python ABI tag数字部分,例如`37`对应`cp37`(`--just_build_whl`时有效)。 | | 48 | | `--py_abi` | 指定whl包的Python ABI tag数字部分,例如`37`对应`cp37`(`--just_build_whl`时有效)。 | |
| 49 | | `--plat_name` | 指定whl包的平台标签,例如`manylinux2014`(`--just_build_whl`时有效)。 | | 49 | | `--plat_name` | 指定whl包的平台标签,例如`manylinux2014`(`--just_build_whl`时有效)。 | |
| 50 | +| `-j` / `--job_num` | 指定编译并行度。不指定时根据CPU核数和可用内存(含cgroup内存上限)自动计算。 | | ||
| 51 | + | ||
| 52 | +> [!NOTE] 并行度与内存 | ||
| 53 | +> | ||
| 54 | +> - 若未指定编译并行度,将默认根据 CPU 核数和可用内存(含 cgroup 内存上限)自动计算。 | ||
| 55 | +> - 也可通过 `-j` 参数或环境变量 `PYPTO_BUILD_JOB_NUM` 显式覆盖,两者在 `pip install .` 和 `build_ci.py` 入口均生效。 | ||
| 50 | 56 | ||
| 51 | ### 安装 | 57 | ### 安装 |
| 52 | 58 | ||
| @@ -28,6 +28,7 @@ class TestCaseArgsParser: | |||
| 28 | logging.info("End index : %s", args.end_index) | 28 | logging.info("End index : %s", args.end_index) |
| 29 | logging.info("Device : %s", args.device) | 29 | logging.info("Device : %s", args.device) |
| 30 | logging.info("Clean : %s", args.clean) | 30 | logging.info("Clean : %s", args.clean) |
| 31 | + logging.info("Job Num : %s", args.job_num) | ||
| 31 | logging.info("Is python case : %s", args.python) | 32 | logging.info("Is python case : %s", args.python) |
| 32 | logging.info("Save data : %s", args.save_data) | 33 | logging.info("Save data : %s", args.save_data) |
| 33 | logging.info("Is json only : %s", args.json_only) | 34 | logging.info("Is json only : %s", args.json_only) |
| @@ -112,6 +113,15 @@ class TestCaseArgsParser: | |||
| 112 | action="store_true", | 113 | action="store_true", |
| 113 | help="clean the compile result.", | 114 | help="clean the compile result.", |
| 114 | ) | 115 | ) |
| 116 | + self._parser.add_argument( | ||
| 117 | + "-j", | ||
| 118 | + "--job_num", | ||
| 119 | + nargs="?", | ||
| 120 | + type=int, | ||
| 121 | + default=None, | ||
| 122 | + help="Build parallelism (job num) passed through to build_ci.py. " | ||
| 123 | + "If unset, the build_ci.py default (CPU + memory aware) is used.", | ||
| 124 | + ) | ||
| 115 | 125 | ||
| 116 | def add_run_args(self): | 126 | def add_run_args(self): |
| 117 | self._parser.add_argument( | 127 | self._parser.add_argument( |
| @@ -36,6 +36,7 @@ class TestCaseLauncher: | |||
| 36 | self.model = config.model | 36 | self.model = config.model |
| 37 | self.json_only = config.json_only | 37 | self.json_only = config.json_only |
| 38 | self.clean = config.clean | 38 | self.clean = config.clean |
| 39 | + self.job_num = config.job_num | ||
| 39 | self.save_data = config.save_data | 40 | self.save_data = config.save_data |
| 40 | self.log_path = os.path.dirname(self.report_file) + "/test_case_log" | 41 | self.log_path = os.path.dirname(self.report_file) + "/test_case_log" |
| 41 | self.plog_cache_path = f"{self.work_path}/plog" | 42 | self.plog_cache_path = f"{self.work_path}/plog" |
| @@ -76,6 +77,8 @@ class TestCaseLauncher: | |||
| 76 | def compile_if_need(self): | 77 | def compile_if_need(self): |
| 77 | clean_str = "-c" if self.clean else "" | 78 | clean_str = "-c" if self.clean else "" |
| 78 | cmd = f"{sys.executable} build_ci.py {clean_str}" | 79 | cmd = f"{sys.executable} build_ci.py {clean_str}" |
| 80 | + if self.job_num and self.job_num > 0: | ||
| 81 | + cmd += f" -j {self.job_num}" | ||
| 79 | if self.python: | 82 | if self.python: |
| 80 | cmd += " -f=python3" | 83 | cmd += " -f=python3" |
| 81 | elif not self.distributed_op: | 84 | elif not self.distributed_op: |
| @@ -88,10 +88,17 @@ class _BuildOnlineManager: | |||
| 88 | 88 | ||
| 89 | @classmethod | 89 | @classmethod |
| 90 | def _which_cmake(cls) -> Optional[Path]: | 90 | def _which_cmake(cls) -> Optional[Path]: |
| 91 | - """查找系统级 CMake 可执行文件路径, 委托至 _which_cmake 公共模块.""" | 91 | + """查找系统级 CMake 可执行文件路径, 排除 cmake pip 包.""" |
| 92 | - from ._which_cmake import which_cmake | 92 | + import importlib.util |
| 93 | 93 | ||
| 94 | - return which_cmake() | 94 | + src_root = Path(__file__).resolve().parents[2] |
| 95 | + mod_path = src_root / "cmake" / "scripts" / "_which_cmake.py" | ||
| 96 | + if mod_path.exists(): | ||
| 97 | + spec = importlib.util.spec_from_file_location("_which_cmake_rt", mod_path) | ||
| 98 | + mod = importlib.util.module_from_spec(spec) | ||
| 99 | + spec.loader.exec_module(mod) | ||
| 100 | + return mod.which_cmake() | ||
| 101 | + return shutil.which("cmake") and Path(shutil.which("cmake")) or None | ||
| 95 | 102 | ||
| 96 | def compile(self, ctx: CompileContext) -> Path: | 103 | def compile(self, ctx: CompileContext) -> Path: |
| 97 | """执行编译流程(包含 CMake 的 Configure, Build 及 Install 阶段) | 104 | """执行编译流程(包含 CMake 的 Configure, Build 及 Install 阶段) |
| @@ -25,8 +25,6 @@ import importlib | |||
| 25 | from importlib import metadata | 25 | from importlib import metadata |
| 26 | import json | 26 | import json |
| 27 | import logging | 27 | import logging |
| 28 | -import math | ||
| 29 | -import multiprocessing | ||
| 30 | import os | 28 | import os |
| 31 | from pathlib import Path | 29 | from pathlib import Path |
| 32 | import re | 30 | import re |
| @@ -45,17 +43,24 @@ from setuptools.command.develop import develop | |||
| 45 | from setuptools.command.editable_wheel import editable_wheel | 43 | from setuptools.command.editable_wheel import editable_wheel |
| 46 | from setuptools.command.egg_info import egg_info | 44 | from setuptools.command.egg_info import egg_info |
| 47 | 45 | ||
| 48 | -# 从 python/pypto/_which_cmake.py 加载公共模块 (不依赖 sys.path) | 46 | +# 从 cmake/scripts/_which_cmake.py 加载公共模块 (不依赖 sys.path) |
| 49 | _script_dir = Path(__file__).resolve().parent | 47 | _script_dir = Path(__file__).resolve().parent |
| 50 | -_which_cmake_path = _script_dir / "python" / "pypto" / "_which_cmake.py" | 48 | +_which_cmake_path = _script_dir / "cmake" / "scripts" / "_which_cmake.py" |
| 51 | _spec = importlib.util.spec_from_file_location("_which_cmake", _which_cmake_path) | 49 | _spec = importlib.util.spec_from_file_location("_which_cmake", _which_cmake_path) |
| 52 | _which_cmake_mod = importlib.util.module_from_spec(_spec) | 50 | _which_cmake_mod = importlib.util.module_from_spec(_spec) |
| 53 | _spec.loader.exec_module(_which_cmake_mod) | 51 | _spec.loader.exec_module(_which_cmake_mod) |
| 54 | which_cmake = _which_cmake_mod.which_cmake | 52 | which_cmake = _which_cmake_mod.which_cmake |
| 55 | 53 | ||
| 54 | +# 从 cmake/scripts/_job_num.py 加载公共模块 (不依赖 sys.path) | ||
| 55 | +_job_num_path = _script_dir / "cmake" / "scripts" / "_job_num.py" | ||
| 56 | +_job_num_spec = importlib.util.spec_from_file_location("_job_num", _job_num_path) | ||
| 57 | +_job_num_mod = importlib.util.module_from_spec(_job_num_spec) | ||
| 58 | +_job_num_spec.loader.exec_module(_job_num_mod) | ||
| 59 | +get_job_num = _job_num_mod.get_job_num | ||
| 60 | + | ||
| 56 | 61 | ||
| 57 | def _find_system_cmake() -> Optional[Path]: | 62 | def _find_system_cmake() -> Optional[Path]: |
| 58 | - """查找系统级 CMake 可执行文件路径, 委托至 pypto._which_cmake 公共模块.""" | 63 | + """查找系统级 CMake 可执行文件路径, 委托至 cmake/scripts/_which_cmake 公共模块.""" |
| 59 | return which_cmake() | 64 | return which_cmake() |
| 60 | 65 | ||
| 61 | 66 | ||
| @@ -435,7 +440,8 @@ class CMakeBuild(build_ext, CMakeUserOption, EditModeHelper): | |||
| 435 | def _get_job_num(job_num: Optional[int], generator: Optional[str]) -> Optional[int]: | 440 | def _get_job_num(job_num: Optional[int], generator: Optional[str]) -> Optional[int]: |
| 436 | """获取构建并行任务数 | 441 | """获取构建并行任务数 |
| 437 | 442 | ||
| 438 | - 根据系统 CPU 核数和构建生成器类型确定合适的并行任务数. 如果使用 Ninja 生成器, 则由 Ninja 自动决定并行度. | 443 | + 委托至 cmake/scripts/_job_num 公共模块, 综合考虑 CPU 核数、可用内存(含 cgroup 上限) |
| 444 | + 及 PYPTO_BUILD_JOB_NUM 环境变量确定并行度. Ninja 生成器时由 Ninja 自身决定. | ||
| 439 | 445 | ||
| 440 | :param job_num: 用户指定的并行任务数 | 446 | :param job_num: 用户指定的并行任务数 |
| 441 | :type job_num: Optional[int] | 447 | :type job_num: Optional[int] |
| @@ -444,18 +450,7 @@ class CMakeBuild(build_ext, CMakeUserOption, EditModeHelper): | |||
| 444 | :return: 并行任务数, None 表示由构建工具自动决定 | 450 | :return: 并行任务数, None 表示由构建工具自动决定 |
| 445 | :rtype: Optional[int] | 451 | :rtype: Optional[int] |
| 446 | """ | 452 | """ |
| 447 | - def_job_num = min(int(math.ceil(float(multiprocessing.cpu_count()) * 0.9)), 128) # 128 为缺省最大核数 | 453 | + return get_job_num(job_num=job_num, generator=generator) |
| 448 | - def_job_num = ( | ||
| 449 | - None | ||
| 450 | - if generator | ||
| 451 | - and generator.lower() | ||
| 452 | - in [ | ||
| 453 | - "ninja", | ||
| 454 | - ] | ||
| 455 | - else def_job_num | ||
| 456 | - ) # ninja 自身决定缺省核数 | ||
| 457 | - job_num = job_num if job_num and job_num > 0 else def_job_num | ||
| 458 | - return job_num | ||
| 459 | 454 | ||
| 460 | @staticmethod | 455 | @staticmethod |
| 461 | def _get_cmake_install_manifest(build_dir: Path, file_name: str = "install_manifest.txt") -> List[str]: | 456 | def _get_cmake_install_manifest(build_dir: Path, file_name: str = "install_manifest.txt") -> List[str]: |