From dcaa573cc2e6f30d346262b3c42d4497a539d90d Mon Sep 17 00:00:00 2001 From: Evan Martin Date: Sat, 28 Jul 2012 13:32:23 -0700 Subject: move processor-count code to util.cc --- src/ninja.cc | 26 +------------------------- src/util.cc | 30 ++++++++++++++++++++++++++++++ src/util.h | 4 ++++ 3 files changed, 35 insertions(+), 25 deletions(-) diff --git a/src/ninja.cc b/src/ninja.cc index 7929e68..ca45ab1 100644 --- a/src/ninja.cc +++ b/src/ninja.cc @@ -19,12 +19,6 @@ #include #include -#if defined(__APPLE__) || defined(__FreeBSD__) -#include -#elif defined(linux) -#include -#endif - #ifdef _WIN32 #include "getopt.h" #include @@ -107,25 +101,7 @@ void Usage(const BuildConfig& config) { /// Choose a default value for the -j (parallelism) flag. int GuessParallelism() { - int processors = 0; - -#if defined(linux) - processors = get_nprocs(); -#elif defined(__APPLE__) || defined(__FreeBSD__) - size_t processors_size = sizeof(processors); - int name[] = {CTL_HW, HW_NCPU}; - if (sysctl(name, sizeof(name) / sizeof(int), - &processors, &processors_size, - NULL, 0) < 0) { - processors = 1; - } -#elif defined(_WIN32) - SYSTEM_INFO info; - GetSystemInfo(&info); - processors = info.dwNumberOfProcessors; -#endif - - switch (processors) { + switch (int processors = GetProcessorCount()) { case 0: case 1: return 2; diff --git a/src/util.cc b/src/util.cc index 10c9dc6..4ce610b 100644 --- a/src/util.cc +++ b/src/util.cc @@ -38,6 +38,12 @@ #include // _mkdir #endif +#if defined(__APPLE__) || defined(__FreeBSD__) +#include +#elif defined(linux) +#include +#endif + #include "edit_distance.h" #include "metrics.h" @@ -283,6 +289,30 @@ string StripAnsiEscapeCodes(const string& in) { return stripped; } +#if defined(linux) +int GetProcessorCount() { + return get_nprocs(); +} +#elif defined(__APPLE__) || defined(__FreeBSD__) +int GetProcessorCount() { + int processors; + size_t processors_size = sizeof(processors); + int name[] = {CTL_HW, HW_NCPU}; + if (sysctl(name, sizeof(name) / sizeof(int), + &processors, &processors_size, + NULL, 0) < 0) { + return 0; + } + return processors; +} +#elif defined(_WIN32) +int GetProcessorCount() { + SYSTEM_INFO info; + GetSystemInfo(&info); + return info.dwNumberOfProcessors; +} +#endif + #ifdef _WIN32 double GetLoadAverage() { // TODO(nicolas.despres@gmail.com): Find a way to implement it on Windows. diff --git a/src/util.h b/src/util.h index 5caf644..9267091 100644 --- a/src/util.h +++ b/src/util.h @@ -62,6 +62,10 @@ const char* SpellcheckString(const string& text, ...); /// Removes all Ansi escape codes (http://www.termsys.demon.co.uk/vtansi.htm). string StripAnsiEscapeCodes(const string& in); +/// @return the number of processors on the machine. Useful for an initial +/// guess for how many jobs to run in parallel. @return 0 on error. +int GetProcessorCount(); + /// @return the load average of the machine. A negative value is returned /// on error. double GetLoadAverage(); -- cgit v0.12