├── .github └── workflows │ ├── build_publish.yml │ └── test_build.yml ├── .gitignore ├── .gitmodules ├── .vscode ├── c_cpp_properties.json └── settings.json ├── CMakeLists.txt ├── LICENSE ├── MANIFEST.in ├── README.md ├── examples ├── feature_check.py ├── get_as_dict.py ├── pprint_info.py └── print_as_table.py ├── pyproject.toml ├── requirements.txt ├── setup.py └── src ├── binding.cc └── py_cpu └── __init__.py /.github/workflows/build_publish.yml: -------------------------------------------------------------------------------- 1 | name: Python package build and publish 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Set up Python 13 | uses: actions/setup-python@v1 14 | with: 15 | python-version: 3.8 16 | - name: Install dependencies 17 | run: | 18 | python -m pip install --upgrade pip 19 | pip install twine flake8 20 | - name: Lint with flake8 for syntax errors 21 | run: | 22 | pip install flake8 23 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 24 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 25 | - name: Build manylinux Python wheels 26 | uses: RalfG/python-wheels-manylinux-build@v0.3.3-manylinux2010_x86_64 27 | with: 28 | python-versions: 'cp36-cp36m cp37-cp37m' 29 | build-requirements: 'cmake scikit-build' 30 | - name: Publish wheels to PyPI 31 | env: 32 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 33 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 34 | run: | 35 | twine upload dist/*-manylinux*.whl 36 | -------------------------------------------------------------------------------- /.github/workflows/test_build.yml: -------------------------------------------------------------------------------- 1 | name: Python package build test 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | python-version: [3.5, 3.6, 3.7, 3.8] 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v2 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | - name: Install dependencies 23 | run: | 24 | python -m pip install --upgrade pip 25 | pip install flake8 pytest 26 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 27 | - name: Lint with flake8 28 | run: | 29 | # stop the build if there are Python syntax errors or undefined names 30 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 31 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 32 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | deps 131 | build 132 | bin 133 | _skbuild -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/pybind11"] 2 | path = src/pybind11 3 | url = https://github.com/pybind/pybind11.git 4 | branch = stable 5 | [submodule "src/cpu_features"] 6 | path = src/cpu_features 7 | url = https://github.com/Narasimha1997/cpu_features.git 8 | -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Linux", 5 | "includePath": [ 6 | "${workspaceFolder}/src/cpu_features/include", 7 | "/usr/include/python3.6m", 8 | "/usr/local/include/python3.6", 9 | "${workspaceFolder}/src/pybind11/include" 10 | ], 11 | "defines": [], 12 | "compilerPath": "/usr/bin/g++", 13 | "cStandard": "c99", 14 | "cppStandard": "c++11", 15 | "intelliSenseMode": "clang-x64" 16 | } 17 | ], 18 | "version": 4 19 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "unordered_map": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.5) 2 | project(py_cpu) 3 | 4 | find_package(Git QUIET) 5 | if(GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git") 6 | # Update submodules as needed 7 | option(GIT_SUBMODULE "Check submodules during build" ON) 8 | if(GIT_SUBMODULE) 9 | message(STATUS "Submodule update") 10 | execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive 11 | WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} 12 | RESULT_VARIABLE GIT_SUBMOD_RESULT) 13 | if(NOT GIT_SUBMOD_RESULT EQUAL "0") 14 | message(FATAL_ERROR "git submodule update --init failed with ${GIT_SUBMOD_RESULT}, please checkout submodules") 15 | endif() 16 | endif() 17 | endif() 18 | 19 | if(NOT EXISTS "${PROJECT_SOURCE_DIR}/src/pybind11/CMakeLists.txt") 20 | message(FATAL_ERROR "The submodules were not downloaded! GIT_SUBMODULE was turned off or failed. Please update submodules and try again.") 21 | endif() 22 | 23 | if(NOT EXISTS "${PROJECT_SOURCE_DIR}/src/cpu_features/CMakeLists.txt") 24 | message(FATAL_ERROR "The submodules were not downloaded! GIT_SUBMODULE was turned off or failed. Please update submodules and try again.") 25 | endif() 26 | 27 | option (BUILD_PIC "Build shared libraries" ON) 28 | set(BUILD_PIC ON) 29 | 30 | add_subdirectory(src/cpu_features) 31 | add_subdirectory(src/pybind11) 32 | 33 | pybind11_add_module(bindings MODULE "src/binding.cc") 34 | target_link_libraries(bindings PRIVATE cpu_features) 35 | 36 | install(TARGETS bindings DESTINATION .) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include src * 2 | recursive-include examples * 3 | include README.md 4 | include CMakeLists.txt 5 | include .git 6 | include .gitignore 7 | include .gitmodules 8 | include LICENSE 9 | include pyproject.toml 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # py_cpu 2 | Python bindings for Google's [cpu_features](https://github.com/google/cpu_features) library. Using this library, Python developers can check for hardware specific features and enable the respective optimizations in their software at runtime. `py_cpu` provides bindings for multiple hardware architectures like `x86`, `ARM`, `AARCH64`, `MIPS` and `PPC`. 3 | 4 | ### Quick start 5 | To use py_cpu, You can directly download and install the pre-built wheel file, using the command below: 6 | ``` 7 | pip install py-cpu 8 | ``` 9 | 10 | (For x86, the pre-built wheel will be installed automatically, on other platforms, the source distribution will be downloaded and the package will be built on the platform natively) 11 | 12 | ### Building from source: 13 | 14 | Requirements: 15 | 1. Python3 16 | 2. CMake 17 | 3. setuptools 18 | 4. wheel 19 | 5. scikit-build 20 | 21 | TO build from source, you can just clone this repository, you need not have to clone the submodules, as they will be downloaded by the cmake build system automatically. 22 | ``` 23 | git clone https://github.com/Narasimha1997/py_cpu.git 24 | ``` 25 | 26 | To directly install the package from the source, use the command below: 27 | ``` 28 | pip install py_cpu/ #-- the repo root directory 29 | ``` 30 | 31 | If you are using an older version of pip, the build-system packages will not be automatically installed, in that case, 32 | ``` 33 | pip install -r py_cpu/requirements.txt #manually install the build requirements 34 | pip install py_cpu/ #then install the package 35 | ``` 36 | 37 | To build `sdist` and `bdist_wheel` you can just run `setup.py` as follows: 38 | ``` 39 | cd py_cpu/ 40 | python3 install sdist bdist_wheel 41 | ``` 42 | 43 | ### Usage guide: 44 | To use the package in your codebase, just import `py_cpu`. 45 | 46 | ``` 47 | import py_cpu 48 | ``` 49 | 50 | #### 1. Get the CPU info 51 | ```python3 52 | import py_cpu 53 | 54 | #get cpu info 55 | cpu_info = py_cpu.CPUInfo() 56 | ``` 57 | 58 | #### 2. Check for features: 59 | ```python3 60 | import py_cpu 61 | 62 | 63 | #call this once during the program init, to avoid unnecessary compute unless required. 64 | cpu_info = py_cpu.CPUInfo() 65 | 66 | #check if the CPU supports AES instructions 67 | if cpu_info.features.aes : 68 | print('Yes, it supports, Run the optimized code') 69 | else : 70 | print('No, run normal code') 71 | 72 | ``` 73 | 74 | #### 3. Get the list of supported features : 75 | ```python3 76 | import py_cpu 77 | cpu_info = py_cpu.CPUInfo() 78 | 79 | #returns a python dictionary, you can check the feature by 80 | # subscripting, example : features_dict['aes'] -> either True or False 81 | features_dict = cpu_info.get_features_as_dict() 82 | print(features_dict['avx']) 83 | 84 | # returns a FeatureFlags object, this is simple to use because you can use . operator instead of subscripting. 85 | 86 | features = cpu_info.get_features() 87 | print(features.avx) 88 | ``` 89 | 90 | #### Get the general info about the hardware 91 | Apart from features and SOCs, you can also query the general info - about architecture type, vendor etc. 92 | These fields are different for different hardware. 93 | 94 | ```python3 95 | import py_cpu 96 | cpu_info = py_cpu.CPUInfo() 97 | 98 | #get list of field names 99 | supported_fields = cpu_info.get_info_fields() 100 | 101 | #example, on x86 102 | # ['arch', 'brand', 'family', 'features', 'model', 'stepping', 'uarch', 'vendor'] 103 | 104 | #query the fields: Because the cpu_info object supports subscripting 105 | 106 | brand_name = cup_info['brand'] 107 | 108 | #if you want the entire object as a dict 109 | info_dict = cpu_info.as_dict() 110 | 111 | #if you want the entire object but exclude features 112 | info_dict_without_features = cpu_info.as_dict(include_features = False) 113 | 114 | ``` 115 | 116 | #### 5. Print functions 117 | If you just want to print the output, you can use any of these two methods. 118 | These methods will be just for a fancy fun use. 119 | 120 | Pretty-Print Dict - This function uses pprint internally. 121 | ```python3 122 | import py_cpu 123 | #obtain CPU info 124 | cpu_info = py_cpu.CPUInfo() 125 | 126 | #call pprint method 127 | cpu_info.pprint() 128 | ``` 129 | 130 | Print as table - This function uses python formatting/spacings to display the list as a table. 131 | ```python3 132 | import py_cpu 133 | #obtain CPU info 134 | cpu_info = py_cpu.CPUInfo() 135 | 136 | #call print_as_table method 137 | cpu_info.print_as_table() 138 | ``` 139 | 140 | ### Guide for developers: 141 | If you want to add new features, this section is for you. 142 | The repository depends on `pybind11` and the original `cpu_features` repository by Google. Both of these are includes as submodules under `src/`. To get the complete codebase, you have to clone the submodules as well. Just run these commands from the project directory : 143 | 144 | ``` 145 | git submodule init 146 | git submodule update 147 | ``` 148 | Or you can clone the repo recursively. 149 | 150 | #### Under the hood details: 151 | The binding code is written in C++ and uses `pybind11` to build a `Cpython` extension. `binding.cc` implements the binding code for all the five platform which are supported in the original repo. Since most of the C/C++ compiler implementations on any operating system expose the architecture flags as preprocessor definitions, only the target hardware binding code gets retained for compilation. The binding code also declares structures that are python friendly - Like STL maps etc to store the data. 152 | The entire structure is a read-only object for python and cannot be modified, this makes the implementation much more easy and faster. During the build-phase, `CMake` first compiles Google's cpu_features library as a submodule and builds a Position independent object code (PIC), since the Cpython extension is a shared dynamic library. Then the target is compiled with Pybind11 to create the final cpython extension. `__init__.py` is just like a glue which provides caching functionality by storing it inside an object, so you can only init once and use it throughout the lifecycle of the application. 153 | 154 | **Note** : This python binding is not an offical Google release. The project respects the license and distribution terms of both `cpu_features` and `pybind11` by adding them as sub-modules - this helps us to keep the original implementation as it is. 155 | 156 | ### Contributing 157 | If you like to contribute code to this repo, you are always welcome. 158 | I would encourage newbies to take up the tasks, as it would allow them to get into the open source world. 159 | Also, please do test it on variety of platforms. Please do raise issues if you have any problems. 160 | -------------------------------------------------------------------------------- /examples/feature_check.py: -------------------------------------------------------------------------------- 1 | import py_cpu 2 | 3 | #get cpu info 4 | cpu_info = py_cpu.CPUInfo() 5 | 6 | #get a list of features table as dict 7 | cpu_info.get_features_as_dict() 8 | 9 | #get a list of features as FeatureFalgs object, supports . operator based checks 10 | cpu_info.get_features() 11 | 12 | #check if your cpu supports AES Instruction set (INTEL-NI) 13 | if cpu_info.features.aes : 14 | print("CPU has instruction sets for AES, dispatch H/W accelerated code optimized code.") 15 | else: 16 | print('CPU does not support AES Instruction set, dispatch S/W defined code.') 17 | -------------------------------------------------------------------------------- /examples/get_as_dict.py: -------------------------------------------------------------------------------- 1 | import py_cpu 2 | 3 | cpu_info = py_cpu.CPUInfo() 4 | 5 | as_dict_data = cpu_info.as_dict() 6 | 7 | print(as_dict_data) -------------------------------------------------------------------------------- /examples/pprint_info.py: -------------------------------------------------------------------------------- 1 | import py_cpu 2 | 3 | #obtain CPU info 4 | cpu_info = py_cpu.CPUInfo() 5 | 6 | #call pprint method 7 | cpu_info.pprint() -------------------------------------------------------------------------------- /examples/print_as_table.py: -------------------------------------------------------------------------------- 1 | import py_cpu 2 | 3 | #obtain CPU info 4 | cpu_info = py_cpu.CPUInfo() 5 | 6 | #call pprint method 7 | cpu_info.print_as_table() 8 | 9 | #subscriptable: 10 | print(cpu_info['arch']) -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | 2 | [build-system] 3 | requires = [ 4 | "setuptools>=42", 5 | "wheel", 6 | "cmake", 7 | "scikit-build" 8 | ] 9 | 10 | build-backend = "setuptools.build_meta" 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | wheel 2 | cmake 3 | setuptools>=42 4 | scikit-build 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from skbuild import setup 2 | 3 | long_description = open('README.md').read() 4 | 5 | setup( 6 | name="py_cpu", 7 | version="0.1.2", 8 | author="Narasimha Prasanna HN", 9 | author_email="narasimhaprasannahn@gmail.com", 10 | description="Python bindings for Google's cpu_features library.", 11 | url="https://github.com/Narasimha1997/py_cpu.git", 12 | license="Apache 2.0 License", 13 | has_package_data=False, 14 | package_dir={"": "src"}, 15 | packages = ["py_cpu"], 16 | cmake_install_dir = "src/py_cpu", 17 | classifiers=[ 18 | 'Development Status :: 4 - Beta', 19 | 'Intended Audience :: Developers', 20 | 'Topic :: System :: Hardware', 21 | 'License :: OSI Approved :: Apache Software License', 22 | 'Programming Language :: Python :: 3', 23 | 'Programming Language :: Python :: 3.2', 24 | 'Programming Language :: Python :: 3.4', 25 | 'Programming Language :: Python :: 3.5', 26 | 'Programming Language :: Python :: 3.6', 27 | 'Programming Language :: Python :: 3.9', 28 | ], 29 | python_requires='>=3', 30 | long_description = long_description, 31 | long_description_content_type = 'text/markdown' 32 | ) -------------------------------------------------------------------------------- /src/binding.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | #include 6 | 7 | //cpu_features 8 | #include "cpu_features_macros.h" 9 | 10 | /* 11 | Architecture specific marcos 12 | */ 13 | 14 | #if defined(CPU_FEATURES_ARCH_X86) 15 | #include "cpuinfo_x86.h" 16 | 17 | typedef struct 18 | { 19 | std::string brand; 20 | std::string vendor; 21 | int family; 22 | int model; 23 | int stepping; 24 | std::string arch; 25 | std::string uarch; 26 | std::unordered_map features; 27 | } x86_CPU; 28 | 29 | x86_CPU GetCPUInfo() 30 | { 31 | const cpu_features::X86Info cpu_info = cpu_features::GetX86Info(); 32 | //set the structure fields : 33 | x86_CPU cpu; 34 | cpu.arch = "x86"; 35 | cpu.vendor = cpu_info.vendor; 36 | cpu.family = cpu_info.family; 37 | cpu.model = cpu_info.model; 38 | cpu.stepping = cpu_info.stepping; 39 | cpu.uarch = cpu_features::GetX86MicroarchitectureName( 40 | cpu_features::GetX86Microarchitecture(&cpu_info)); 41 | 42 | for (int i = 0; i < cpu_features::X86_LAST_; i++) 43 | { 44 | const auto enum_val = static_cast(i); 45 | std::pair feature_pair( 46 | cpu_features::GetX86FeaturesEnumName(enum_val), 47 | cpu_features::GetX86FeaturesEnumValue(&cpu_info.features, enum_val)); 48 | cpu.features.insert(feature_pair); 49 | } 50 | 51 | //set brand string 52 | char brand[49]; 53 | cpu_features::FillX86BrandString(brand); 54 | 55 | cpu.brand = brand; 56 | 57 | return cpu; 58 | } 59 | 60 | PYBIND11_MODULE(bindings, mod) 61 | { 62 | mod.doc() = "Cross-platform CPU features library. Built on Google's cpu_features."; 63 | 64 | //Bind the feature-map 65 | pybind11::bind_map>(mod, "Features"); 66 | 67 | auto classExporter = pybind11::class_(mod, "CpuInfo"); 68 | 69 | classExporter.def(pybind11::init<>()); 70 | classExporter.def_readonly("arch", &x86_CPU::arch); 71 | classExporter.def_readonly("brand", &x86_CPU::brand); 72 | classExporter.def_readonly("vendor", &x86_CPU::vendor); 73 | classExporter.def_readonly("family", &x86_CPU::family); 74 | classExporter.def_readonly("model", &x86_CPU::model); 75 | classExporter.def_readonly("stepping", &x86_CPU::stepping); 76 | classExporter.def_readonly("uarch", &x86_CPU::uarch); 77 | classExporter.def_readonly("features", &x86_CPU::features); 78 | 79 | //Add platform-specific CPU Info function 80 | mod.def("get_cpu_info", &GetCPUInfo, "Get cpu features."); 81 | } 82 | 83 | #elif defined(CPU_FEATURES_ARCH_ARM) 84 | #include "cpuinfo_arm.h" 85 | 86 | typedef struct 87 | { 88 | int implementer; 89 | int architecture; 90 | int variant; 91 | int part; 92 | int revision; 93 | std::unordered_map features; 94 | } ARM_CPU; 95 | 96 | ARM_CPU GetCPUInfo() 97 | { 98 | const cpu_features::ArmInfo cpu_info = cpu_features::GetArmInfo(); 99 | ARM_CPU cpu; 100 | cpu.implementer = cpu_info.implementer; 101 | cpu.architecture = cpu_info.architecture; 102 | cpu.variant = cpu_info.variant; 103 | cpu.part = cpu_info.part; 104 | cpu.revision = cpu_info.revision; 105 | 106 | for (int i = 0; i < cpu_features::ARM_LAST_; i++) 107 | { 108 | const auto enum_val = static_cast(i); 109 | std::pair feature_pair( 110 | cpu_features::GetArmFeaturesEnumName(enum_val), 111 | cpu_features::GetArmFeaturesEnumValue(&cpu_info.features, enum_val)); 112 | cpu.features.insert(feature_pair); 113 | } 114 | 115 | return cpu; 116 | } 117 | 118 | PYBIND11_MODULE(bindings, mod) 119 | { 120 | mod.doc() = "Cross-platform CPU features library. Built on Google's cpu_features."; 121 | 122 | //Bind the feature-map 123 | pybind11::bind_map>(mod, "Features"); 124 | 125 | auto classExporter = pybind11::class_(mod, "CpuInfo"); 126 | 127 | classExporter.def(pybind11::init<>()); 128 | classExporter.def_readonly("implementer", &ARM_CPU::implementer); 129 | classExporter.def_readonly("architecture", &ARM_CPU::architecture); 130 | classExporter.def_readonly("variant", &ARM_CPU::variant); 131 | classExporter.def_readonly("revision", &ARM_CPU::revision); 132 | classExporter.def_readonly("part", &ARM_CPU::part); 133 | classExporter.def_readonly("arch", &ARM_CPU::arch); 134 | 135 | classExporter.def_readonly("features", &ARM_CPU::features); 136 | 137 | //Add platform-specific CPU Info function 138 | mod.def("get_cpu_info", &GetCPUInfo, "Get cpu features."); 139 | } 140 | 141 | #elif defined(CPU_FEATURES_ARCH_AARCH64) 142 | #include "cpuinfo_aarch64.h" 143 | 144 | typedef struct 145 | { 146 | std::unordered_map features; 147 | int implementer; 148 | int variant; 149 | int part; 150 | int revision; 151 | std::string arch; 152 | } AARCH_CPU; 153 | 154 | AARCH_CPU GetCpuInfo() 155 | { 156 | const cpu_features::Aarch64Info cpu_info = cpu_features::GetAarch64Info(); 157 | AARCH_CPU cpu; 158 | 159 | cpu.arch = "aarch64"; 160 | cpu.variant = cpu_info.variant; 161 | cpu.implementer = cpu_info.implementer; 162 | cpu.part = cpu_info.part; 163 | cpu.revision = cpu.revision; 164 | 165 | for (int i = 0; i < cpu_features::AARCH64_LAST_; i++) 166 | { 167 | const auto enum_val = static_cast(i); 168 | std::pair feature_pair( 169 | cpu_features::GetAarch64FeaturesEnumName(enum_val), 170 | cpu_features::GetAarch64FeaturesEnumValue(&cpu_info.features, enum_val)); 171 | cpu.features.insert(feature_pair); 172 | } 173 | 174 | return cpu; 175 | } 176 | 177 | PYBIND11_MODULE(bindings, mod) 178 | { 179 | mod.doc() = "Cross-platform CPU features library. Built on Google's cpu_features."; 180 | 181 | //Bind the feature-map 182 | pybind11::bind_map>(mod, "Features"); 183 | 184 | auto classExporter = pybind11::class_(mod, "CpuInfo"); 185 | 186 | classExporter.def(pybind11::init<>()); 187 | classExporter.def_readonly("implementer", &AARCH_CPU::implementer); 188 | classExporter.def_readonly("variant", &AARCH_CPU::variant); 189 | classExporter.def_readonly("revision", &AARCH_CPU::revision); 190 | classExporter.def_readonly("part", &AARCH_CPU::part); 191 | classExporter.def_readonly("arch", &AARCH_CPU::arch); 192 | 193 | classExporter.def_readonly("features", &AARCH_CPU::features); 194 | 195 | //Add platform-specific CPU Info function 196 | mod.def("get_cpu_info", &GetCpuInfo, "Get cpu features."); 197 | } 198 | 199 | #elif defined(CPU_FEATURES_ARCH_MIPS) 200 | #include "cpuinfo_mips.h" 201 | 202 | typedef struct 203 | { 204 | std::string arch; 205 | std::unordered_map features; 206 | } MIPS_CPU; 207 | 208 | MIPS_CPU GetCpuInfo() 209 | { 210 | const cpu_features::MipsInfo cpu_info = cpu_features::GetMipsInfo(); 211 | MIPS_CPU cpu; 212 | 213 | cpu.arch = "mips"; 214 | for (int i = 0; i < cpu_features::MIPS_LAST_; i++) 215 | { 216 | const auto enum_val = static_cast(i); 217 | std::pair feature_pair( 218 | cpu_features::GetMipsFeaturesEnumName(enum_val), 219 | cpu_features::GetMipsFeaturesEnumValue(&cpu_info.features, enum_val)); 220 | cpu.features.insert(feature_pair); 221 | } 222 | 223 | return cpu; 224 | } 225 | 226 | PYBIND11_MODULE(bindings, mod) 227 | { 228 | mod.doc() = "Cross-platform CPU features library. Built on Google's cpu_features."; 229 | 230 | //Bind the feature-map 231 | pybind11::bind_map>(mod, "Features"); 232 | 233 | auto classExporter = pybind11::class_(mod, "CpuInfo"); 234 | 235 | classExporter.def(pybind11::init<>()); 236 | classExporter.def_readonly("arch", &MIPS_CPU::arch); 237 | classExporter.def_readonly("features", &MIPS_CPU::features); 238 | 239 | //Add platform-specific CPU Info function 240 | mod.def("get_cpu_info", &GetCpuInfo, "Get cpu features."); 241 | } 242 | 243 | #elif defined(CPU_FEATURES_ARCH_PPC) 244 | #include "cpuinfo_ppc.h" 245 | 246 | typedef struct 247 | { 248 | std::string platform; 249 | std::string model; 250 | std::string machine; 251 | std::string cpu; 252 | std::string base_platform; 253 | std::string arch; 254 | std::unordered_map features; 255 | } PPC_CPU; 256 | 257 | PPC_CPU GetCpuInfo() 258 | { 259 | const cpu_features::PPCInfo cpu_info = cpu_features::GetPPCInfo(); 260 | const cpu_features::PPCPlatformStrings platform = cpu_features::GetPPCPlatformStrings(); 261 | 262 | PPC_CPU cpu; 263 | 264 | cpu.arch = "ppc"; 265 | cpu.platform = platform.platform; 266 | cpu.machine = platform.machine; 267 | cpu.model = platform.model; 268 | cpu.cpu = platform.cpu; 269 | cpu.base_platform = platform.type.base_platform; 270 | 271 | for (int i = 0; i < cpu_features::PPC_LAST_; i++) 272 | { 273 | const auto enum_val = static_cast(i); 274 | std::pair feature_pair( 275 | cpu_features::GetPPCFeaturesEnumName(enum_val), 276 | cpu_features::GetPPCFeaturesEnumValue(&cpu_info.features, enum_val)); 277 | cpu.features.insert(feature_pair); 278 | } 279 | 280 | return cpu; 281 | } 282 | 283 | PYBIND11_MODULE(bindings, mod) 284 | { 285 | mod.doc() = "Cross-platform CPU features library. Built on Google's cpu_features."; 286 | 287 | //Bind the feature-map 288 | pybind11::bind_map>(mod, "Features"); 289 | 290 | auto classExporter = pybind11::class_(mod, "CpuInfo"); 291 | 292 | classExporter.def(pybind11::init<>()); 293 | classExporter.def_readonly("platform", &PPC_CPU::platform); 294 | classExporter.def_readonly("model", &PPC_CPU::model); 295 | classExporter.def_readonly("machine", &PPC_CPU::machine); 296 | classExporter.def_readonly("cpu", &PPC_CPU::cpu); 297 | classExporter.def_readonly("base_platform", &PPC_CPU::base_platform); 298 | classExporter.def_readonly("arch", &PPC_CPU::arch); 299 | 300 | classExporter.def_readonly("features", &PPC_CPU::features); 301 | 302 | //Add platform-specific CPU Info function 303 | mod.def("get_cpu_info", &GetCpuInfo, "Get cpu features."); 304 | } 305 | 306 | #endif -------------------------------------------------------------------------------- /src/py_cpu/__init__.py: -------------------------------------------------------------------------------- 1 | from .bindings import get_cpu_info 2 | import pprint 3 | 4 | __all__ = ['CPUInfo'] 5 | 6 | 7 | class FeatureFlags(dict): 8 | def __init__(self, *args, **kwargs): 9 | super(FeatureFlags, self).__init__(*args, **kwargs) 10 | self.__dict__ = self 11 | 12 | 13 | class CPUInfo(): 14 | 15 | def __init__(self): 16 | 17 | # load cpu info 18 | self.cpu_info = get_cpu_info() 19 | self.features = FeatureFlags(self.cpu_info.features.items()) 20 | 21 | def as_dict(self, include_features=True): 22 | 23 | info_dict = {} 24 | for _attr in dir(self.cpu_info): 25 | if _attr == "features": 26 | if not include_features: 27 | continue 28 | info_dict['features'] = self.features 29 | elif not _attr.startswith("_"): 30 | info_dict[_attr] = getattr(self.cpu_info, _attr) 31 | 32 | return info_dict 33 | 34 | def get_info_fields(self): 35 | 36 | info_fields = [] 37 | for _attr in dir(self.cpu_info): 38 | if not _attr.startswith("_"): 39 | info_fields.append(_attr) 40 | 41 | return info_fields 42 | 43 | def pprint(self): 44 | dict_type = self.as_dict() 45 | pprint.pprint(dict_type) 46 | 47 | def get_features(self): 48 | return self.features 49 | 50 | def get_features_as_dict(self): 51 | return dict(self.features) 52 | 53 | def print_as_table(self): 54 | print("CPU Description:") 55 | print("--------------------------------------") 56 | print("{:<15} {:<10}".format('Label', 'Value')) 57 | print("--------------------------------------") 58 | for _att in dir(self.cpu_info): 59 | if _att.startswith("_") or _att == "features": 60 | continue 61 | print("{:<15} {:<10}".format(_att, getattr(self.cpu_info, _att))) 62 | 63 | print("\nCPU Features:") 64 | print("--------------------------------------------------------") 65 | print("{:<30} {:<20}".format('Feature Name', 'Is supported?')) 66 | print("--------------------------------------------------------") 67 | for key, value in sorted(self.features.items()): 68 | print("{:<30} {:<20}".format(key, "Yes" if value else "No")) 69 | 70 | def __getitem__(self, attr): 71 | return getattr(self.cpu_info, attr) 72 | --------------------------------------------------------------------------------