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 /// Memory usage limit for encoding
30 static uint64_t memlimit_encoder;
32 /// Memory usage limit for decoding
33 static uint64_t memlimit_decoder;
35 /// Memory usage limit given on the command line or environment variable.
36 /// Zero indicates the default (memlimit_encoder or memlimit_decoder).
37 static uint64_t memlimit_custom = 0;
40 /// Get the number of CPU cores, and set opt_threads to default to that value.
41 /// User can then override this with --threads command line option.
45 #if defined(HAVE_NUM_PROCESSORS_SYSCONF)
46 const long cpus = sysconf(_SC_NPROCESSORS_ONLN);
48 opt_threads = (size_t)(cpus);
50 #elif defined(HAVE_NUM_PROCESSORS_SYSCTL)
51 int name[2] = { CTL_HW, HW_NCPU };
53 size_t cpus_size = sizeof(cpus);
54 if (!sysctl(name, &cpus, &cpus_size, NULL, NULL)
55 && cpus_size == sizeof(cpus) && cpus > 0)
56 opt_threads = (size_t)(cpus);
59 // Limit opt_threads so that maximum number of threads doesn't exceed.
61 #if defined(_SC_THREAD_THREADS_MAX)
62 const long threads_max = sysconf(_SC_THREAD_THREADS_MAX);
63 if (threads_max > 0 && (size_t)(threads_max) < opt_threads)
64 opt_threads = (size_t)(threads_max);
66 #elif defined(PTHREAD_THREADS_MAX)
67 if (opt_threads > PTHREAD_THREADS_MAX)
68 opt_threads = PTHREAD_THREADS_MAX;
76 hardware_memlimit_init(void)
78 uint64_t mem = physmem();
80 // If we cannot determine the amount of RAM, assume 32 MiB. Maybe
81 // even that is too much on some systems. But on most systems it's
82 // far too little, and can be annoying.
84 mem = UINT64_C(16) * 1024 * 1024;
86 // Use at maximum of 90 % of RAM when encoding and 33 % when decoding.
87 memlimit_encoder = mem - mem / 10;
88 memlimit_decoder = mem / 3;
95 hardware_memlimit_set(uint64_t memlimit)
97 memlimit_custom = memlimit;
103 hardware_memlimit_encoder(void)
105 return memlimit_custom != 0 ? memlimit_custom : memlimit_encoder;
110 hardware_memlimit_decoder(void)
112 return memlimit_custom != 0 ? memlimit_custom : memlimit_decoder;
119 hardware_memlimit_init();