num_cpus-1.11.1/.appveyor.yml010066400017500001750000000006471311163042500143200ustar0000000000000000environment: matrix: - TARGET: x86_64-pc-windows-msvc - TARGET: i686-pc-windows-msvc - TARGET: x86_64-pc-windows-gnu - TARGET: i686-pc-windows-gnu install: - curl -sSf -o rustup-init.exe https://win.rustup.rs/ - rustup-init.exe -y --default-host %TARGET% - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - rustc -vV - cargo -vV build: false test_script: - cargo build --verbose - cargo test --verbose num_cpus-1.11.1/.gitignore010066400017500001750000000000221250161602400136260ustar0000000000000000target Cargo.lock num_cpus-1.11.1/.travis.yml010066400017500001750000000033361343511251100137610ustar0000000000000000language: rust rust: stable dist: trusty sudo: false cache: cargo install: - if [ -z "$NO_ADD" ]; then rustup target add "$TARGET"; fi script: - cargo build --verbose --target "$TARGET" # Only run the targets if we are on the same OS. - if [ "$RUN" == "1" ]; then cargo test --verbose --target "$TARGET"; fi env: global: # Travis CI servers make 2 cores available to processes via virtualization. # See https://docs.travis-ci.com/user/reference/overview/ - NUM_CPUS_TEST_GET=2 matrix: include: # Linux # 32-bit requires multilib. - env: TARGET=i686-unknown-linux-gnu RUN=1 addons: apt: packages: - gcc-multilib # 64-bit stable. - env: TARGET=x86_64-unknown-linux-gnu RUN=1 NO_ADD=1 rust: stable # 64-bit beta. - env: TARGET=x86_64-unknown-linux-gnu RUN=1 NO_ADD=1 rust: beta # 64-bit nightly. - env: TARGET=x86_64-unknown-linux-gnu RUN=1 NO_ADD=1 rust: nightly # Mac OS X - os: osx env: TARGET=i686-apple-darwin RUN=1 - os: osx env: TARGET=x86_64-apple-darwin RUN=1 NO_ADD=1 # Android # - for x86 - env: TARGET=i686-linux-android - env: TARGET=x86_64-linux-android # - for ARM - env: TARGET=arm-linux-androideabi - env: TARGET=aarch64-linux-android # IOS - os: osx osx_image: xcode9 env: TARGET=i386-apple-ios - os: osx osx_image: xcode9 env: TARGET=x86_64-apple-ios # FreeBSD - env: TARGET=x86_64-unknown-freebsd # Fuchsia # FIXME: figure out why target is missing and re-enable #- env: TARGET=x86_64-unknown-fuchsia # NetBSD - env: TARGET=x86_64-unknown-netbsd # Emscripten - env: TARGET=asmjs-unknown-emscripten num_cpus-1.11.1/CHANGELOG.md010066400017500001750000000027241356257372300135020ustar0000000000000000## v1.11.1 #### Fixes - Use `mem::zeroed` instead of `mem::uninitialized`. ## v1.11.0 #### Features - add `hermit` target OS support - removes `bitrig` support #### Fixes - fix `get_physical` count with AMD hyperthreading. ## v1.10.1 #### Fixes - improve `haiku` CPU detection ## v1.10.0 #### Features - add `illumos` target OS support - add default fallback if target is unknown to `1` ## v1.9.0 #### Features - add `sgx` target env support ## v1.8.0 #### Features - add `wasm-unknown-unknown` target support ## v1.7.0 #### Features - add `get_physical` support for macOS #### Fixes - use `_SC_NPROCESSORS_CONF` on Unix targets ### v1.6.2 #### Fixes - revert 1.6.1 for now ### v1.6.1 #### Fixes - fixes sometimes incorrect num on Android/ARM Linux (#45) ## v1.6.0 #### Features - `get_physical` gains Windows support ### v1.5.1 #### Fixes - fix `get` to return 1 if `sysconf(_SC_NPROCESSORS_ONLN)` failed ## v1.5.0 #### Features - `get()` now checks `sched_affinity` on Linux ## v1.4.0 #### Features - add `haiku` target support ## v1.3.0 #### Features - add `redox` target support ### v1.2.1 #### Fixes - fixes `get_physical` count (454ff1b) ## v1.2.0 #### Features - add `emscripten` target support - add `fuchsia` target support ## v1.1.0 #### Features - added `get_physical` function to return number of physical CPUs found # v1.0.0 #### Features - `get` function returns number of CPUs (physical and virtual) of current platform num_cpus-1.11.1/CONTRIBUTING.md010066400017500001750000000010011316323012000140570ustar0000000000000000# Contributing ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. num_cpus-1.11.1/Cargo.toml.orig010066400017500001750000000011421356257363300145510ustar0000000000000000[package] name = "num_cpus" version = "1.11.1" # don't forget to update html_root_url description = "Get the number of CPUs on a machine." authors = ["Sean McArthur "] license = "MIT/Apache-2.0" repository = "https://github.com/seanmonstar/num_cpus" documentation = "https://docs.rs/num_cpus" keywords = ["cpu", "cpus", "cores"] categories = ["hardware-support"] readme = "README.md" [dependencies] libc = "0.2.26" [target.'cfg(all(any(target_arch = "x86_64", target_arch = "aarch64"), target_os = "hermit"))'.dependencies] hermit-abi = "0.1.3" [dev-dependencies] doc-comment = "0.3" num_cpus-1.11.1/Cargo.toml0000644000000021421356257377700110670ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "num_cpus" version = "1.11.1" authors = ["Sean McArthur "] description = "Get the number of CPUs on a machine." documentation = "https://docs.rs/num_cpus" readme = "README.md" keywords = ["cpu", "cpus", "cores"] categories = ["hardware-support"] license = "MIT/Apache-2.0" repository = "https://github.com/seanmonstar/num_cpus" [dependencies.libc] version = "0.2.26" [dev-dependencies.doc-comment] version = "0.3" [target."cfg(all(any(target_arch = \"x86_64\", target_arch = \"aarch64\"), target_os = \"hermit\"))".dependencies.hermit-abi] version = "0.1.3" num_cpus-1.11.1/LICENSE-APACHE010066400017500001750000000251371271466300700136110ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. num_cpus-1.11.1/LICENSE-MIT010066400017500001750000000020241271466300700133070ustar0000000000000000Copyright (c) 2015 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. num_cpus-1.11.1/README.md010066400017500001750000000013251316323212100131210ustar0000000000000000# num_cpus [![crates.io](http://meritbadge.herokuapp.com/num_cpus)](https://crates.io/crates/num_cpus) [![Travis CI Status](https://travis-ci.org/seanmonstar/num_cpus.svg?branch=master)](https://travis-ci.org/seanmonstar/num_cpus) [![AppVeyor status](https://ci.appveyor.com/api/projects/status/qn8t6grhko5jwno6?svg=true)](https://ci.appveyor.com/project/seanmonstar/num-cpus) - [Documentation](https://docs.rs/num_cpus) - [CHANGELOG](CHANGELOG.md) Count the number of CPUs on the current machine. ## Usage Add to Cargo.toml: ```toml [dependencies] num_cpus = "1.0" ``` In your `main.rs` or `lib.rs`: ```rust extern crate num_cpus; // count logical cores this process could try to use let num = num_cpus::get(); ``` num_cpus-1.11.1/examples/values.rs010066400017500001750000000002261347747725300153550ustar0000000000000000extern crate num_cpus; fn main() { println!("Logical CPUs: {}", num_cpus::get()); println!("Physical CPUs: {}", num_cpus::get_physical()); } num_cpus-1.11.1/src/lib.rs010066400017500001750000000331331356257364600135760ustar0000000000000000//! A crate with utilities to determine the number of CPUs available on the //! current system. //! //! Sometimes the CPU will exaggerate the number of CPUs it contains, because it can use //! [processor tricks] to deliver increased performance when there are more threads. This //! crate provides methods to get both the logical and physical numbers of cores. //! //! This information can be used as a guide to how many tasks can be run in parallel. //! There are many properties of the system architecture that will affect parallelism, //! for example memory access speeds (for all the caches and RAM) and the physical //! architecture of the processor, so the number of CPUs should be used as a rough guide //! only. //! //! //! ## Examples //! //! Fetch the number of logical CPUs. //! //! ``` //! let cpus = num_cpus::get(); //! ``` //! //! See [`rayon::Threadpool`] for an example of where the number of CPUs could be //! used when setting up parallel jobs (Where the threadpool example uses a fixed //! number 8, it could use the number of CPUs). //! //! [processor tricks]: https://en.wikipedia.org/wiki/Simultaneous_multithreading //! [`rayon::ThreadPool`]: https://docs.rs/rayon/1.*/rayon/struct.ThreadPool.html #![cfg_attr(test, deny(warnings))] #![deny(missing_docs)] #![doc(html_root_url = "https://docs.rs/num_cpus/1.11.1")] #![allow(non_snake_case)] #[cfg(not(windows))] extern crate libc; #[cfg(target_os = "hermit")] extern crate hermit_abi; #[cfg(test)] #[macro_use] extern crate doc_comment; #[cfg(test)] doctest!("../README.md"); /// Returns the number of available CPUs of the current system. /// /// This function will get the number of logical cores. Sometimes this is different from the number /// of physical cores (See [Simultaneous multithreading on Wikipedia][smt]). /// /// # Examples /// /// ``` /// let cpus = num_cpus::get(); /// if cpus > 1 { /// println!("We are on a multicore system with {} CPUs", cpus); /// } else { /// println!("We are on a single core system"); /// } /// ``` /// /// # Note /// /// This will check [sched affinity] on Linux, showing a lower number of CPUs if the current /// thread does not have access to all the computer's CPUs. /// /// [smt]: https://en.wikipedia.org/wiki/Simultaneous_multithreading /// [sched affinity]: http://www.gnu.org/software/libc/manual/html_node/CPU-Affinity.html #[inline] pub fn get() -> usize { get_num_cpus() } /// Returns the number of physical cores of the current system. /// /// # Note /// /// Physical count is supported only on Linux, mac OS and Windows platforms. /// On other platforms, or if the physical count fails on supported platforms, /// this function returns the same as [`get()`], which is the number of logical /// CPUS. /// /// # Examples /// /// ``` /// let logical_cpus = num_cpus::get(); /// let physical_cpus = num_cpus::get_physical(); /// if logical_cpus > physical_cpus { /// println!("We have simultaneous multithreading with about {:.2} \ /// logical cores to 1 physical core.", /// (logical_cpus as f64) / (physical_cpus as f64)); /// } else if logical_cpus == physical_cpus { /// println!("Either we don't have simultaneous multithreading, or our \ /// system doesn't support getting the number of physical CPUs."); /// } else { /// println!("We have less logical CPUs than physical CPUs, maybe we only have access to \ /// some of the CPUs on our system."); /// } /// ``` /// /// [`get()`]: fn.get.html #[inline] pub fn get_physical() -> usize { get_num_physical_cpus() } #[cfg(not(any(target_os = "linux", target_os = "windows", target_os="macos")))] #[inline] fn get_num_physical_cpus() -> usize { // Not implemented, fall back get_num_cpus() } #[cfg(target_os = "windows")] fn get_num_physical_cpus() -> usize { match get_num_physical_cpus_windows() { Some(num) => num, None => get_num_cpus() } } #[cfg(target_os = "windows")] fn get_num_physical_cpus_windows() -> Option { // Inspired by https://msdn.microsoft.com/en-us/library/ms683194 use std::ptr; use std::mem; #[allow(non_upper_case_globals)] const RelationProcessorCore: u32 = 0; #[repr(C)] #[allow(non_camel_case_types)] struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION { mask: usize, relationship: u32, _unused: [u64; 2] } extern "system" { fn GetLogicalProcessorInformation( info: *mut SYSTEM_LOGICAL_PROCESSOR_INFORMATION, length: &mut u32 ) -> u32; } // First we need to determine how much space to reserve. // The required size of the buffer, in bytes. let mut needed_size = 0; unsafe { GetLogicalProcessorInformation(ptr::null_mut(), &mut needed_size); } let struct_size = mem::size_of::() as u32; // Could be 0, or some other bogus size. if needed_size == 0 || needed_size < struct_size || needed_size % struct_size != 0 { return None; } let count = needed_size / struct_size; // Allocate some memory where we will store the processor info. let mut buf = Vec::with_capacity(count as usize); let result; unsafe { result = GetLogicalProcessorInformation(buf.as_mut_ptr(), &mut needed_size); } // Failed for any reason. if result == 0 { return None; } let count = needed_size / struct_size; unsafe { buf.set_len(count as usize); } let phys_proc_count = buf.iter() // Only interested in processor packages (physical processors.) .filter(|proc_info| proc_info.relationship == RelationProcessorCore) .count(); if phys_proc_count == 0 { None } else { Some(phys_proc_count) } } #[cfg(target_os = "linux")] fn get_num_physical_cpus() -> usize { use std::collections::HashMap; use std::fs::File; use std::io::BufRead; use std::io::BufReader; let file = match File::open("/proc/cpuinfo") { Ok(val) => val, Err(_) => return get_num_cpus(), }; let reader = BufReader::new(file); let mut map = HashMap::new(); let mut physid: u32 = 0; let mut cores: usize = 0; let mut chgcount = 0; for line in reader.lines().filter_map(|result| result.ok()) { let mut it = line.split(':'); let (key, value) = match (it.next(), it.next()) { (Some(key), Some(value)) => (key.trim(), value.trim()), _ => continue, }; if key == "physical id" { match value.parse() { Ok(val) => physid = val, Err(_) => break, }; chgcount += 1; } if key == "cpu cores" { match value.parse() { Ok(val) => cores = val, Err(_) => break, }; chgcount += 1; } if chgcount == 2 { map.insert(physid, cores); chgcount = 0; } } let count = map.into_iter().fold(0, |acc, (_, cores)| acc + cores); if count == 0 { get_num_cpus() } else { count } } #[cfg(windows)] fn get_num_cpus() -> usize { #[repr(C)] struct SYSTEM_INFO { wProcessorArchitecture: u16, wReserved: u16, dwPageSize: u32, lpMinimumApplicationAddress: *mut u8, lpMaximumApplicationAddress: *mut u8, dwActiveProcessorMask: *mut u8, dwNumberOfProcessors: u32, dwProcessorType: u32, dwAllocationGranularity: u32, wProcessorLevel: u16, wProcessorRevision: u16, } extern "system" { fn GetSystemInfo(lpSystemInfo: *mut SYSTEM_INFO); } unsafe { let mut sysinfo: SYSTEM_INFO = std::mem::zeroed(); GetSystemInfo(&mut sysinfo); sysinfo.dwNumberOfProcessors as usize } } #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] fn get_num_cpus() -> usize { use std::ptr; let mut cpus: libc::c_uint = 0; let mut cpus_size = std::mem::size_of_val(&cpus); unsafe { cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint; } if cpus < 1 { let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0]; unsafe { libc::sysctl(mib.as_mut_ptr(), 2, &mut cpus as *mut _ as *mut _, &mut cpus_size as *mut _ as *mut _, ptr::null_mut(), 0); } if cpus < 1 { cpus = 1; } } cpus as usize } #[cfg(target_os = "openbsd")] fn get_num_cpus() -> usize { use std::ptr; let mut cpus: libc::c_uint = 0; let mut cpus_size = std::mem::size_of_val(&cpus); let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0]; unsafe { libc::sysctl(mib.as_mut_ptr(), 2, &mut cpus as *mut _ as *mut _, &mut cpus_size as *mut _ as *mut _, ptr::null_mut(), 0); } if cpus < 1 { cpus = 1; } cpus as usize } #[cfg(target_os = "macos")] fn get_num_physical_cpus() -> usize { use std::ffi::CStr; use std::ptr; let mut cpus: i32 = 0; let mut cpus_size = std::mem::size_of_val(&cpus); let sysctl_name = CStr::from_bytes_with_nul(b"hw.physicalcpu\0") .expect("byte literal is missing NUL"); unsafe { if 0 != libc::sysctlbyname(sysctl_name.as_ptr(), &mut cpus as *mut _ as *mut _, &mut cpus_size as *mut _ as *mut _, ptr::null_mut(), 0) { return get_num_cpus(); } } cpus as usize } #[cfg(target_os = "linux")] fn get_num_cpus() -> usize { let mut set: libc::cpu_set_t = unsafe { std::mem::zeroed() }; if unsafe { libc::sched_getaffinity(0, std::mem::size_of::(), &mut set) } == 0 { let mut count: u32 = 0; for i in 0..libc::CPU_SETSIZE as usize { if unsafe { libc::CPU_ISSET(i, &set) } { count += 1 } } count as usize } else { let cpus = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }; if cpus < 1 { 1 } else { cpus as usize } } } #[cfg(any( target_os = "nacl", target_os = "macos", target_os = "ios", target_os = "android", target_os = "solaris", target_os = "illumos", target_os = "fuchsia") )] fn get_num_cpus() -> usize { // On ARM targets, processors could be turned off to save power. // Use `_SC_NPROCESSORS_CONF` to get the real number. #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] const CONF_NAME: libc::c_int = libc::_SC_NPROCESSORS_CONF; #[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))] const CONF_NAME: libc::c_int = libc::_SC_NPROCESSORS_ONLN; let cpus = unsafe { libc::sysconf(CONF_NAME) }; if cpus < 1 { 1 } else { cpus as usize } } #[cfg(target_os = "haiku")] fn get_num_cpus() -> usize { use std::mem; #[allow(non_camel_case_types)] type bigtime_t = i64; #[allow(non_camel_case_types)] type status_t = i32; #[repr(C)] pub struct system_info { pub boot_time: bigtime_t, pub cpu_count: u32, pub max_pages: u64, pub used_pages: u64, pub cached_pages: u64, pub block_cache_pages: u64, pub ignored_pages: u64, pub needed_memory: u64, pub free_memory: u64, pub max_swap_pages: u64, pub free_swap_pages: u64, pub page_faults: u32, pub max_sems: u32, pub used_sems: u32, pub max_ports: u32, pub used_ports: u32, pub max_threads: u32, pub used_threads: u32, pub max_teams: u32, pub used_teams: u32, pub kernel_name: [::std::os::raw::c_char; 256usize], pub kernel_build_date: [::std::os::raw::c_char; 32usize], pub kernel_build_time: [::std::os::raw::c_char; 32usize], pub kernel_version: i64, pub abi: u32, } extern { fn get_system_info(info: *mut system_info) -> status_t; } let mut info: system_info = unsafe { mem::zeroed() }; let status = unsafe { get_system_info(&mut info as *mut _) }; if status == 0 { info.cpu_count as usize } else { 1 } } #[cfg(target_os = "hermit")] fn get_num_cpus() -> usize { unsafe { hermit_abi::get_processor_count() } } #[cfg(not(any( target_os = "nacl", target_os = "macos", target_os = "ios", target_os = "android", target_os = "solaris", target_os = "illumos", target_os = "fuchsia", target_os = "linux", target_os = "openbsd", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "haiku", target_os = "hermit", windows, )))] fn get_num_cpus() -> usize { 1 } #[cfg(test)] mod tests { fn env_var(name: &'static str) -> Option { ::std::env::var(name).ok().map(|val| val.parse().unwrap()) } #[test] fn test_get() { let num = super::get(); if let Some(n) = env_var("NUM_CPUS_TEST_GET") { assert_eq!(num, n); } else { assert!(num > 0); assert!(num < 236_451); } } #[test] fn test_get_physical() { let num = super::get_physical(); if let Some(n) = env_var("NUM_CPUS_TEST_GET_PHYSICAL") { assert_eq!(num, n); } else { assert!(num > 0); assert!(num < 236_451); } } } num_cpus-1.11.1/.cargo_vcs_info.json0000644000000001121356257377700130640ustar00{ "git": { "sha1": "428811d2a00920479fdb7dc9e9e2902e52e92e4b" } } num_cpus-1.11.1/Cargo.lock0000644000000024101356257377700110420ustar00# This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "doc-comment" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "hermit-abi" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "libc" version = "0.2.65" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "num_cpus" version = "1.11.1" dependencies = [ "doc-comment 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "hermit-abi 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", ] [metadata] "checksum doc-comment 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "923dea538cea0aa3025e8685b20d6ee21ef99c4f77e954a30febbaac5ec73a97" "checksum hermit-abi 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "307c3c9f937f38e3534b1d6447ecf090cafcc9744e4a6360e8b037b2cf5af120" "checksum libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)" = "1a31a0627fdf1f6a39ec0dd577e101440b7db22672c0901fe00a9a6fbb5c24e8"