1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief Detection of available hardware resources
6 // Copyright (C) 2007 Lasse Collin
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Lesser General Public
10 // License as published by the Free Software Foundation; either
11 // version 2.1 of the License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // Lesser General Public License for more details.
18 ///////////////////////////////////////////////////////////////////////////////
24 /// Maximum number of free *coder* threads. This can be set with
25 /// the --threads=NUM command line option.
26 size_t opt_threads = 1;
29 /// Number of bytes of memory to use at maximum (only a rough limit).
30 /// This can be set with the --memory=NUM command line option.
31 /// If no better value can be determined, the default is 14 MiB, which
32 /// should be quite safe even for older systems while still allowing
33 /// reasonable compression ratio.
34 size_t opt_memory = 14 * 1024 * 1024;
37 /// Get the amount of physical memory, and set opt_memory to 1/3 of it.
38 /// User can then override this with --memory command line option.
42 uint64_t mem = physmem();
46 #if UINT64_MAX > SIZE_MAX
58 /// Get the number of CPU cores, and set opt_threads to default to that value.
59 /// User can then override this with --threads command line option.
63 #if defined(HAVE_NUM_PROCESSORS_SYSCONF)
64 const long cpus = sysconf(_SC_NPROCESSORS_ONLN);
66 opt_threads = (size_t)(cpus);
68 #elif defined(HAVE_NUM_PROCESSORS_SYSCTL)
69 int name[2] = { CTL_HW, HW_NCPU };
71 size_t cpus_size = sizeof(cpus);
72 if (!sysctl(name, &cpus, &cpus_size, NULL, NULL)
73 && cpus_size == sizeof(cpus) && cpus > 0)
74 opt_threads = (size_t)(cpus);
77 // Limit opt_threads so that maximum number of threads doesn't exceed.
79 #if defined(_SC_THREAD_THREADS_MAX)
80 const long threads_max = sysconf(_SC_THREAD_THREADS_MAX);
81 if (threads_max > 0 && (size_t)(threads_max) < opt_threads)
82 opt_threads = (size_t)(threads_max);
84 #elif defined(PTHREAD_THREADS_MAX)
85 if (opt_threads > PTHREAD_THREADS_MAX)
86 opt_threads = PTHREAD_THREADS_MAX;