nanobenchmark.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. // Copyright 2017 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/random/internal/nanobenchmark.h"
  15. #include <sys/types.h>
  16. #include <algorithm> // sort
  17. #include <atomic>
  18. #include <cstddef>
  19. #include <cstdint>
  20. #include <cstdlib>
  21. #include <cstring> // memcpy
  22. #include <limits>
  23. #include <string>
  24. #include <utility>
  25. #include <vector>
  26. #include "absl/base/attributes.h"
  27. #include "absl/base/internal/raw_logging.h"
  28. #include "absl/random/internal/platform.h"
  29. #include "absl/random/internal/randen_engine.h"
  30. // OS
  31. #if defined(_WIN32) || defined(_WIN64)
  32. #define ABSL_OS_WIN
  33. #include <windows.h> // NOLINT
  34. #elif defined(__ANDROID__)
  35. #define ABSL_OS_ANDROID
  36. #elif defined(__linux__)
  37. #define ABSL_OS_LINUX
  38. #include <sched.h> // NOLINT
  39. #include <sys/syscall.h> // NOLINT
  40. #endif
  41. #if defined(ABSL_ARCH_X86_64) && !defined(ABSL_OS_WIN)
  42. #include <cpuid.h> // NOLINT
  43. #endif
  44. // __ppc_get_timebase_freq
  45. #if defined(ABSL_ARCH_PPC)
  46. #include <sys/platform/ppc.h> // NOLINT
  47. #endif
  48. // clock_gettime
  49. #if defined(ABSL_ARCH_ARM) || defined(ABSL_ARCH_AARCH64)
  50. #include <time.h> // NOLINT
  51. #endif
  52. // ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE prevents inlining of the method.
  53. #if ABSL_HAVE_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__))
  54. #define ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE __attribute__((noinline))
  55. #elif defined(_MSC_VER)
  56. #define ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE __declspec(noinline)
  57. #else
  58. #define ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE
  59. #endif
  60. namespace absl {
  61. ABSL_NAMESPACE_BEGIN
  62. namespace random_internal_nanobenchmark {
  63. namespace {
  64. // For code folding.
  65. namespace platform {
  66. #if defined(ABSL_ARCH_X86_64)
  67. // TODO(janwas): Merge with the one in randen_hwaes.cc?
  68. void Cpuid(const uint32_t level, const uint32_t count,
  69. uint32_t* ABSL_RANDOM_INTERNAL_RESTRICT abcd) {
  70. #if defined(ABSL_OS_WIN)
  71. int regs[4];
  72. __cpuidex(regs, level, count);
  73. for (int i = 0; i < 4; ++i) {
  74. abcd[i] = regs[i];
  75. }
  76. #else
  77. uint32_t a, b, c, d;
  78. __cpuid_count(level, count, a, b, c, d);
  79. abcd[0] = a;
  80. abcd[1] = b;
  81. abcd[2] = c;
  82. abcd[3] = d;
  83. #endif
  84. }
  85. std::string BrandString() {
  86. char brand_string[49];
  87. uint32_t abcd[4];
  88. // Check if brand string is supported (it is on all reasonable Intel/AMD)
  89. Cpuid(0x80000000U, 0, abcd);
  90. if (abcd[0] < 0x80000004U) {
  91. return std::string();
  92. }
  93. for (int i = 0; i < 3; ++i) {
  94. Cpuid(0x80000002U + i, 0, abcd);
  95. memcpy(brand_string + i * 16, &abcd, sizeof(abcd));
  96. }
  97. brand_string[48] = 0;
  98. return brand_string;
  99. }
  100. // Returns the frequency quoted inside the brand string. This does not
  101. // account for throttling nor Turbo Boost.
  102. double NominalClockRate() {
  103. const std::string& brand_string = BrandString();
  104. // Brand strings include the maximum configured frequency. These prefixes are
  105. // defined by Intel CPUID documentation.
  106. const char* prefixes[3] = {"MHz", "GHz", "THz"};
  107. const double multipliers[3] = {1E6, 1E9, 1E12};
  108. for (size_t i = 0; i < 3; ++i) {
  109. const size_t pos_prefix = brand_string.find(prefixes[i]);
  110. if (pos_prefix != std::string::npos) {
  111. const size_t pos_space = brand_string.rfind(' ', pos_prefix - 1);
  112. if (pos_space != std::string::npos) {
  113. const std::string digits =
  114. brand_string.substr(pos_space + 1, pos_prefix - pos_space - 1);
  115. return std::stod(digits) * multipliers[i];
  116. }
  117. }
  118. }
  119. return 0.0;
  120. }
  121. #endif // ABSL_ARCH_X86_64
  122. } // namespace platform
  123. // Prevents the compiler from eliding the computations that led to "output".
  124. template <class T>
  125. inline void PreventElision(T&& output) {
  126. #ifndef ABSL_OS_WIN
  127. // Works by indicating to the compiler that "output" is being read and
  128. // modified. The +r constraint avoids unnecessary writes to memory, but only
  129. // works for built-in types (typically FuncOutput).
  130. asm volatile("" : "+r"(output) : : "memory");
  131. #else
  132. // MSVC does not support inline assembly anymore (and never supported GCC's
  133. // RTL constraints). Self-assignment with #pragma optimize("off") might be
  134. // expected to prevent elision, but it does not with MSVC 2015. Type-punning
  135. // with volatile pointers generates inefficient code on MSVC 2017.
  136. static std::atomic<T> dummy(T{});
  137. dummy.store(output, std::memory_order_relaxed);
  138. #endif
  139. }
  140. namespace timer {
  141. // Start/Stop return absolute timestamps and must be placed immediately before
  142. // and after the region to measure. We provide separate Start/Stop functions
  143. // because they use different fences.
  144. //
  145. // Background: RDTSC is not 'serializing'; earlier instructions may complete
  146. // after it, and/or later instructions may complete before it. 'Fences' ensure
  147. // regions' elapsed times are independent of such reordering. The only
  148. // documented unprivileged serializing instruction is CPUID, which acts as a
  149. // full fence (no reordering across it in either direction). Unfortunately
  150. // the latency of CPUID varies wildly (perhaps made worse by not initializing
  151. // its EAX input). Because it cannot reliably be deducted from the region's
  152. // elapsed time, it must not be included in the region to measure (i.e.
  153. // between the two RDTSC).
  154. //
  155. // The newer RDTSCP is sometimes described as serializing, but it actually
  156. // only serves as a half-fence with release semantics. Although all
  157. // instructions in the region will complete before the final timestamp is
  158. // captured, subsequent instructions may leak into the region and increase the
  159. // elapsed time. Inserting another fence after the final RDTSCP would prevent
  160. // such reordering without affecting the measured region.
  161. //
  162. // Fortunately, such a fence exists. The LFENCE instruction is only documented
  163. // to delay later loads until earlier loads are visible. However, Intel's
  164. // reference manual says it acts as a full fence (waiting until all earlier
  165. // instructions have completed, and delaying later instructions until it
  166. // completes). AMD assigns the same behavior to MFENCE.
  167. //
  168. // We need a fence before the initial RDTSC to prevent earlier instructions
  169. // from leaking into the region, and arguably another after RDTSC to avoid
  170. // region instructions from completing before the timestamp is recorded.
  171. // When surrounded by fences, the additional RDTSCP half-fence provides no
  172. // benefit, so the initial timestamp can be recorded via RDTSC, which has
  173. // lower overhead than RDTSCP because it does not read TSC_AUX. In summary,
  174. // we define Start = LFENCE/RDTSC/LFENCE; Stop = RDTSCP/LFENCE.
  175. //
  176. // Using Start+Start leads to higher variance and overhead than Stop+Stop.
  177. // However, Stop+Stop includes an LFENCE in the region measurements, which
  178. // adds a delay dependent on earlier loads. The combination of Start+Stop
  179. // is faster than Start+Start and more consistent than Stop+Stop because
  180. // the first LFENCE already delayed subsequent loads before the measured
  181. // region. This combination seems not to have been considered in prior work:
  182. // http://akaros.cs.berkeley.edu/lxr/akaros/kern/arch/x86/rdtsc_test.c
  183. //
  184. // Note: performance counters can measure 'exact' instructions-retired or
  185. // (unhalted) cycle counts. The RDPMC instruction is not serializing and also
  186. // requires fences. Unfortunately, it is not accessible on all OSes and we
  187. // prefer to avoid kernel-mode drivers. Performance counters are also affected
  188. // by several under/over-count errata, so we use the TSC instead.
  189. // Returns a 64-bit timestamp in unit of 'ticks'; to convert to seconds,
  190. // divide by InvariantTicksPerSecond.
  191. inline uint64_t Start64() {
  192. uint64_t t;
  193. #if defined(ABSL_ARCH_PPC)
  194. asm volatile("mfspr %0, %1" : "=r"(t) : "i"(268));
  195. #elif defined(ABSL_ARCH_X86_64)
  196. #if defined(ABSL_OS_WIN)
  197. _ReadWriteBarrier();
  198. _mm_lfence();
  199. _ReadWriteBarrier();
  200. t = __rdtsc();
  201. _ReadWriteBarrier();
  202. _mm_lfence();
  203. _ReadWriteBarrier();
  204. #else
  205. asm volatile(
  206. "lfence\n\t"
  207. "rdtsc\n\t"
  208. "shl $32, %%rdx\n\t"
  209. "or %%rdx, %0\n\t"
  210. "lfence"
  211. : "=a"(t)
  212. :
  213. // "memory" avoids reordering. rdx = TSC >> 32.
  214. // "cc" = flags modified by SHL.
  215. : "rdx", "memory", "cc");
  216. #endif
  217. #else
  218. // Fall back to OS - unsure how to reliably query cntvct_el0 frequency.
  219. timespec ts;
  220. clock_gettime(CLOCK_REALTIME, &ts);
  221. t = ts.tv_sec * 1000000000LL + ts.tv_nsec;
  222. #endif
  223. return t;
  224. }
  225. inline uint64_t Stop64() {
  226. uint64_t t;
  227. #if defined(ABSL_ARCH_X86_64)
  228. #if defined(ABSL_OS_WIN)
  229. _ReadWriteBarrier();
  230. unsigned aux;
  231. t = __rdtscp(&aux);
  232. _ReadWriteBarrier();
  233. _mm_lfence();
  234. _ReadWriteBarrier();
  235. #else
  236. // Use inline asm because __rdtscp generates code to store TSC_AUX (ecx).
  237. asm volatile(
  238. "rdtscp\n\t"
  239. "shl $32, %%rdx\n\t"
  240. "or %%rdx, %0\n\t"
  241. "lfence"
  242. : "=a"(t)
  243. :
  244. // "memory" avoids reordering. rcx = TSC_AUX. rdx = TSC >> 32.
  245. // "cc" = flags modified by SHL.
  246. : "rcx", "rdx", "memory", "cc");
  247. #endif
  248. #else
  249. t = Start64();
  250. #endif
  251. return t;
  252. }
  253. // Returns a 32-bit timestamp with about 4 cycles less overhead than
  254. // Start64. Only suitable for measuring very short regions because the
  255. // timestamp overflows about once a second.
  256. inline uint32_t Start32() {
  257. uint32_t t;
  258. #if defined(ABSL_ARCH_X86_64)
  259. #if defined(ABSL_OS_WIN)
  260. _ReadWriteBarrier();
  261. _mm_lfence();
  262. _ReadWriteBarrier();
  263. t = static_cast<uint32_t>(__rdtsc());
  264. _ReadWriteBarrier();
  265. _mm_lfence();
  266. _ReadWriteBarrier();
  267. #else
  268. asm volatile(
  269. "lfence\n\t"
  270. "rdtsc\n\t"
  271. "lfence"
  272. : "=a"(t)
  273. :
  274. // "memory" avoids reordering. rdx = TSC >> 32.
  275. : "rdx", "memory");
  276. #endif
  277. #else
  278. t = static_cast<uint32_t>(Start64());
  279. #endif
  280. return t;
  281. }
  282. inline uint32_t Stop32() {
  283. uint32_t t;
  284. #if defined(ABSL_ARCH_X86_64)
  285. #if defined(ABSL_OS_WIN)
  286. _ReadWriteBarrier();
  287. unsigned aux;
  288. t = static_cast<uint32_t>(__rdtscp(&aux));
  289. _ReadWriteBarrier();
  290. _mm_lfence();
  291. _ReadWriteBarrier();
  292. #else
  293. // Use inline asm because __rdtscp generates code to store TSC_AUX (ecx).
  294. asm volatile(
  295. "rdtscp\n\t"
  296. "lfence"
  297. : "=a"(t)
  298. :
  299. // "memory" avoids reordering. rcx = TSC_AUX. rdx = TSC >> 32.
  300. : "rcx", "rdx", "memory");
  301. #endif
  302. #else
  303. t = static_cast<uint32_t>(Stop64());
  304. #endif
  305. return t;
  306. }
  307. } // namespace timer
  308. namespace robust_statistics {
  309. // Sorts integral values in ascending order (e.g. for Mode). About 3x faster
  310. // than std::sort for input distributions with very few unique values.
  311. template <class T>
  312. void CountingSort(T* values, size_t num_values) {
  313. // Unique values and their frequency (similar to flat_map).
  314. using Unique = std::pair<T, int>;
  315. std::vector<Unique> unique;
  316. for (size_t i = 0; i < num_values; ++i) {
  317. const T value = values[i];
  318. const auto pos =
  319. std::find_if(unique.begin(), unique.end(),
  320. [value](const Unique u) { return u.first == value; });
  321. if (pos == unique.end()) {
  322. unique.push_back(std::make_pair(value, 1));
  323. } else {
  324. ++pos->second;
  325. }
  326. }
  327. // Sort in ascending order of value (pair.first).
  328. std::sort(unique.begin(), unique.end());
  329. // Write that many copies of each unique value to the array.
  330. T* ABSL_RANDOM_INTERNAL_RESTRICT p = values;
  331. for (const auto& value_count : unique) {
  332. std::fill(p, p + value_count.second, value_count.first);
  333. p += value_count.second;
  334. }
  335. ABSL_RAW_CHECK(p == values + num_values, "Did not produce enough output");
  336. }
  337. // @return i in [idx_begin, idx_begin + half_count) that minimizes
  338. // sorted[i + half_count] - sorted[i].
  339. template <typename T>
  340. size_t MinRange(const T* const ABSL_RANDOM_INTERNAL_RESTRICT sorted,
  341. const size_t idx_begin, const size_t half_count) {
  342. T min_range = (std::numeric_limits<T>::max)();
  343. size_t min_idx = 0;
  344. for (size_t idx = idx_begin; idx < idx_begin + half_count; ++idx) {
  345. ABSL_RAW_CHECK(sorted[idx] <= sorted[idx + half_count], "Not sorted");
  346. const T range = sorted[idx + half_count] - sorted[idx];
  347. if (range < min_range) {
  348. min_range = range;
  349. min_idx = idx;
  350. }
  351. }
  352. return min_idx;
  353. }
  354. // Returns an estimate of the mode by calling MinRange on successively
  355. // halved intervals. "sorted" must be in ascending order. This is the
  356. // Half Sample Mode estimator proposed by Bickel in "On a fast, robust
  357. // estimator of the mode", with complexity O(N log N). The mode is less
  358. // affected by outliers in highly-skewed distributions than the median.
  359. // The averaging operation below assumes "T" is an unsigned integer type.
  360. template <typename T>
  361. T ModeOfSorted(const T* const ABSL_RANDOM_INTERNAL_RESTRICT sorted,
  362. const size_t num_values) {
  363. size_t idx_begin = 0;
  364. size_t half_count = num_values / 2;
  365. while (half_count > 1) {
  366. idx_begin = MinRange(sorted, idx_begin, half_count);
  367. half_count >>= 1;
  368. }
  369. const T x = sorted[idx_begin + 0];
  370. if (half_count == 0) {
  371. return x;
  372. }
  373. ABSL_RAW_CHECK(half_count == 1, "Should stop at half_count=1");
  374. const T average = (x + sorted[idx_begin + 1] + 1) / 2;
  375. return average;
  376. }
  377. // Returns the mode. Side effect: sorts "values".
  378. template <typename T>
  379. T Mode(T* values, const size_t num_values) {
  380. CountingSort(values, num_values);
  381. return ModeOfSorted(values, num_values);
  382. }
  383. template <typename T, size_t N>
  384. T Mode(T (&values)[N]) {
  385. return Mode(&values[0], N);
  386. }
  387. // Returns the median value. Side effect: sorts "values".
  388. template <typename T>
  389. T Median(T* values, const size_t num_values) {
  390. ABSL_RAW_CHECK(num_values != 0, "Empty input");
  391. std::sort(values, values + num_values);
  392. const size_t half = num_values / 2;
  393. // Odd count: return middle
  394. if (num_values % 2) {
  395. return values[half];
  396. }
  397. // Even count: return average of middle two.
  398. return (values[half] + values[half - 1] + 1) / 2;
  399. }
  400. // Returns a robust measure of variability.
  401. template <typename T>
  402. T MedianAbsoluteDeviation(const T* values, const size_t num_values,
  403. const T median) {
  404. ABSL_RAW_CHECK(num_values != 0, "Empty input");
  405. std::vector<T> abs_deviations;
  406. abs_deviations.reserve(num_values);
  407. for (size_t i = 0; i < num_values; ++i) {
  408. const int64_t abs = std::abs(int64_t(values[i]) - int64_t(median));
  409. abs_deviations.push_back(static_cast<T>(abs));
  410. }
  411. return Median(abs_deviations.data(), num_values);
  412. }
  413. } // namespace robust_statistics
  414. // Ticks := platform-specific timer values (CPU cycles on x86). Must be
  415. // unsigned to guarantee wraparound on overflow. 32 bit timers are faster to
  416. // read than 64 bit.
  417. using Ticks = uint32_t;
  418. // Returns timer overhead / minimum measurable difference.
  419. Ticks TimerResolution() {
  420. // Nested loop avoids exceeding stack/L1 capacity.
  421. Ticks repetitions[Params::kTimerSamples];
  422. for (size_t rep = 0; rep < Params::kTimerSamples; ++rep) {
  423. Ticks samples[Params::kTimerSamples];
  424. for (size_t i = 0; i < Params::kTimerSamples; ++i) {
  425. const Ticks t0 = timer::Start32();
  426. const Ticks t1 = timer::Stop32();
  427. samples[i] = t1 - t0;
  428. }
  429. repetitions[rep] = robust_statistics::Mode(samples);
  430. }
  431. return robust_statistics::Mode(repetitions);
  432. }
  433. static const Ticks timer_resolution = TimerResolution();
  434. // Estimates the expected value of "lambda" values with a variable number of
  435. // samples until the variability "rel_mad" is less than "max_rel_mad".
  436. template <class Lambda>
  437. Ticks SampleUntilStable(const double max_rel_mad, double* rel_mad,
  438. const Params& p, const Lambda& lambda) {
  439. auto measure_duration = [&lambda]() -> Ticks {
  440. const Ticks t0 = timer::Start32();
  441. lambda();
  442. const Ticks t1 = timer::Stop32();
  443. return t1 - t0;
  444. };
  445. // Choose initial samples_per_eval based on a single estimated duration.
  446. Ticks est = measure_duration();
  447. static const double ticks_per_second = InvariantTicksPerSecond();
  448. const size_t ticks_per_eval = ticks_per_second * p.seconds_per_eval;
  449. size_t samples_per_eval = ticks_per_eval / est;
  450. samples_per_eval = (std::max)(samples_per_eval, p.min_samples_per_eval);
  451. std::vector<Ticks> samples;
  452. samples.reserve(1 + samples_per_eval);
  453. samples.push_back(est);
  454. // Percentage is too strict for tiny differences, so also allow a small
  455. // absolute "median absolute deviation".
  456. const Ticks max_abs_mad = (timer_resolution + 99) / 100;
  457. *rel_mad = 0.0; // ensure initialized
  458. for (size_t eval = 0; eval < p.max_evals; ++eval, samples_per_eval *= 2) {
  459. samples.reserve(samples.size() + samples_per_eval);
  460. for (size_t i = 0; i < samples_per_eval; ++i) {
  461. const Ticks r = measure_duration();
  462. samples.push_back(r);
  463. }
  464. if (samples.size() >= p.min_mode_samples) {
  465. est = robust_statistics::Mode(samples.data(), samples.size());
  466. } else {
  467. // For "few" (depends also on the variance) samples, Median is safer.
  468. est = robust_statistics::Median(samples.data(), samples.size());
  469. }
  470. ABSL_RAW_CHECK(est != 0, "Estimator returned zero duration");
  471. // Median absolute deviation (mad) is a robust measure of 'variability'.
  472. const Ticks abs_mad = robust_statistics::MedianAbsoluteDeviation(
  473. samples.data(), samples.size(), est);
  474. *rel_mad = static_cast<double>(static_cast<int>(abs_mad)) / est;
  475. if (*rel_mad <= max_rel_mad || abs_mad <= max_abs_mad) {
  476. if (p.verbose) {
  477. ABSL_RAW_LOG(INFO,
  478. "%6zu samples => %5u (abs_mad=%4u, rel_mad=%4.2f%%)\n",
  479. samples.size(), est, abs_mad, *rel_mad * 100.0);
  480. }
  481. return est;
  482. }
  483. }
  484. if (p.verbose) {
  485. ABSL_RAW_LOG(WARNING,
  486. "rel_mad=%4.2f%% still exceeds %4.2f%% after %6zu samples.\n",
  487. *rel_mad * 100.0, max_rel_mad * 100.0, samples.size());
  488. }
  489. return est;
  490. }
  491. using InputVec = std::vector<FuncInput>;
  492. // Returns vector of unique input values.
  493. InputVec UniqueInputs(const FuncInput* inputs, const size_t num_inputs) {
  494. InputVec unique(inputs, inputs + num_inputs);
  495. std::sort(unique.begin(), unique.end());
  496. unique.erase(std::unique(unique.begin(), unique.end()), unique.end());
  497. return unique;
  498. }
  499. // Returns how often we need to call func for sufficient precision, or zero
  500. // on failure (e.g. the elapsed time is too long for a 32-bit tick count).
  501. size_t NumSkip(const Func func, const void* arg, const InputVec& unique,
  502. const Params& p) {
  503. // Min elapsed ticks for any input.
  504. Ticks min_duration = ~0u;
  505. for (const FuncInput input : unique) {
  506. // Make sure a 32-bit timer is sufficient.
  507. const uint64_t t0 = timer::Start64();
  508. PreventElision(func(arg, input));
  509. const uint64_t t1 = timer::Stop64();
  510. const uint64_t elapsed = t1 - t0;
  511. if (elapsed >= (1ULL << 30)) {
  512. ABSL_RAW_LOG(WARNING,
  513. "Measurement failed: need 64-bit timer for input=%zu\n",
  514. static_cast<size_t>(input));
  515. return 0;
  516. }
  517. double rel_mad;
  518. const Ticks total = SampleUntilStable(
  519. p.target_rel_mad, &rel_mad, p,
  520. [func, arg, input]() { PreventElision(func(arg, input)); });
  521. min_duration = (std::min)(min_duration, total - timer_resolution);
  522. }
  523. // Number of repetitions required to reach the target resolution.
  524. const size_t max_skip = p.precision_divisor;
  525. // Number of repetitions given the estimated duration.
  526. const size_t num_skip =
  527. min_duration == 0 ? 0 : (max_skip + min_duration - 1) / min_duration;
  528. if (p.verbose) {
  529. ABSL_RAW_LOG(INFO, "res=%u max_skip=%zu min_dur=%u num_skip=%zu\n",
  530. timer_resolution, max_skip, min_duration, num_skip);
  531. }
  532. return num_skip;
  533. }
  534. // Replicates inputs until we can omit "num_skip" occurrences of an input.
  535. InputVec ReplicateInputs(const FuncInput* inputs, const size_t num_inputs,
  536. const size_t num_unique, const size_t num_skip,
  537. const Params& p) {
  538. InputVec full;
  539. if (num_unique == 1) {
  540. full.assign(p.subset_ratio * num_skip, inputs[0]);
  541. return full;
  542. }
  543. full.reserve(p.subset_ratio * num_skip * num_inputs);
  544. for (size_t i = 0; i < p.subset_ratio * num_skip; ++i) {
  545. full.insert(full.end(), inputs, inputs + num_inputs);
  546. }
  547. absl::random_internal::randen_engine<uint32_t> rng;
  548. std::shuffle(full.begin(), full.end(), rng);
  549. return full;
  550. }
  551. // Copies the "full" to "subset" in the same order, but with "num_skip"
  552. // randomly selected occurrences of "input_to_skip" removed.
  553. void FillSubset(const InputVec& full, const FuncInput input_to_skip,
  554. const size_t num_skip, InputVec* subset) {
  555. const size_t count = std::count(full.begin(), full.end(), input_to_skip);
  556. // Generate num_skip random indices: which occurrence to skip.
  557. std::vector<uint32_t> omit;
  558. // Replacement for std::iota, not yet available in MSVC builds.
  559. omit.reserve(count);
  560. for (size_t i = 0; i < count; ++i) {
  561. omit.push_back(i);
  562. }
  563. // omit[] is the same on every call, but that's OK because they identify the
  564. // Nth instance of input_to_skip, so the position within full[] differs.
  565. absl::random_internal::randen_engine<uint32_t> rng;
  566. std::shuffle(omit.begin(), omit.end(), rng);
  567. omit.resize(num_skip);
  568. std::sort(omit.begin(), omit.end());
  569. uint32_t occurrence = ~0u; // 0 after preincrement
  570. size_t idx_omit = 0; // cursor within omit[]
  571. size_t idx_subset = 0; // cursor within *subset
  572. for (const FuncInput next : full) {
  573. if (next == input_to_skip) {
  574. ++occurrence;
  575. // Haven't removed enough already
  576. if (idx_omit < num_skip) {
  577. // This one is up for removal
  578. if (occurrence == omit[idx_omit]) {
  579. ++idx_omit;
  580. continue;
  581. }
  582. }
  583. }
  584. if (idx_subset < subset->size()) {
  585. (*subset)[idx_subset++] = next;
  586. }
  587. }
  588. ABSL_RAW_CHECK(idx_subset == subset->size(), "idx_subset not at end");
  589. ABSL_RAW_CHECK(idx_omit == omit.size(), "idx_omit not at end");
  590. ABSL_RAW_CHECK(occurrence == count - 1, "occurrence not at end");
  591. }
  592. // Returns total ticks elapsed for all inputs.
  593. Ticks TotalDuration(const Func func, const void* arg, const InputVec* inputs,
  594. const Params& p, double* max_rel_mad) {
  595. double rel_mad;
  596. const Ticks duration =
  597. SampleUntilStable(p.target_rel_mad, &rel_mad, p, [func, arg, inputs]() {
  598. for (const FuncInput input : *inputs) {
  599. PreventElision(func(arg, input));
  600. }
  601. });
  602. *max_rel_mad = (std::max)(*max_rel_mad, rel_mad);
  603. return duration;
  604. }
  605. // (Nearly) empty Func for measuring timer overhead/resolution.
  606. ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE FuncOutput
  607. EmptyFunc(const void* arg, const FuncInput input) {
  608. return input;
  609. }
  610. // Returns overhead of accessing inputs[] and calling a function; this will
  611. // be deducted from future TotalDuration return values.
  612. Ticks Overhead(const void* arg, const InputVec* inputs, const Params& p) {
  613. double rel_mad;
  614. // Zero tolerance because repeatability is crucial and EmptyFunc is fast.
  615. return SampleUntilStable(0.0, &rel_mad, p, [arg, inputs]() {
  616. for (const FuncInput input : *inputs) {
  617. PreventElision(EmptyFunc(arg, input));
  618. }
  619. });
  620. }
  621. } // namespace
  622. void PinThreadToCPU(int cpu) {
  623. // We might migrate to another CPU before pinning below, but at least cpu
  624. // will be one of the CPUs on which this thread ran.
  625. #if defined(ABSL_OS_WIN)
  626. if (cpu < 0) {
  627. cpu = static_cast<int>(GetCurrentProcessorNumber());
  628. ABSL_RAW_CHECK(cpu >= 0, "PinThreadToCPU detect failed");
  629. if (cpu >= 64) {
  630. // NOTE: On wine, at least, GetCurrentProcessorNumber() sometimes returns
  631. // a value > 64, which is out of range. When this happens, log a message
  632. // and don't set a cpu affinity.
  633. ABSL_RAW_LOG(ERROR, "Invalid CPU number: %d", cpu);
  634. return;
  635. }
  636. } else if (cpu >= 64) {
  637. // User specified an explicit CPU affinity > the valid range.
  638. ABSL_RAW_LOG(FATAL, "Invalid CPU number: %d", cpu);
  639. }
  640. const DWORD_PTR prev = SetThreadAffinityMask(GetCurrentThread(), 1ULL << cpu);
  641. ABSL_RAW_CHECK(prev != 0, "SetAffinity failed");
  642. #elif defined(ABSL_OS_LINUX) && !defined(ABSL_OS_ANDROID)
  643. if (cpu < 0) {
  644. cpu = sched_getcpu();
  645. ABSL_RAW_CHECK(cpu >= 0, "PinThreadToCPU detect failed");
  646. }
  647. const pid_t pid = 0; // current thread
  648. cpu_set_t set;
  649. CPU_ZERO(&set);
  650. CPU_SET(cpu, &set);
  651. const int err = sched_setaffinity(pid, sizeof(set), &set);
  652. ABSL_RAW_CHECK(err == 0, "SetAffinity failed");
  653. #endif
  654. }
  655. // Returns tick rate. Invariant means the tick counter frequency is independent
  656. // of CPU throttling or sleep. May be expensive, caller should cache the result.
  657. double InvariantTicksPerSecond() {
  658. #if defined(ABSL_ARCH_PPC)
  659. return __ppc_get_timebase_freq();
  660. #elif defined(ABSL_ARCH_X86_64)
  661. // We assume the TSC is invariant; it is on all recent Intel/AMD CPUs.
  662. return platform::NominalClockRate();
  663. #else
  664. // Fall back to clock_gettime nanoseconds.
  665. return 1E9;
  666. #endif
  667. }
  668. size_t MeasureImpl(const Func func, const void* arg, const size_t num_skip,
  669. const InputVec& unique, const InputVec& full,
  670. const Params& p, Result* results) {
  671. const float mul = 1.0f / static_cast<int>(num_skip);
  672. InputVec subset(full.size() - num_skip);
  673. const Ticks overhead = Overhead(arg, &full, p);
  674. const Ticks overhead_skip = Overhead(arg, &subset, p);
  675. if (overhead < overhead_skip) {
  676. ABSL_RAW_LOG(WARNING, "Measurement failed: overhead %u < %u\n", overhead,
  677. overhead_skip);
  678. return 0;
  679. }
  680. if (p.verbose) {
  681. ABSL_RAW_LOG(INFO, "#inputs=%5zu,%5zu overhead=%5u,%5u\n", full.size(),
  682. subset.size(), overhead, overhead_skip);
  683. }
  684. double max_rel_mad = 0.0;
  685. const Ticks total = TotalDuration(func, arg, &full, p, &max_rel_mad);
  686. for (size_t i = 0; i < unique.size(); ++i) {
  687. FillSubset(full, unique[i], num_skip, &subset);
  688. const Ticks total_skip = TotalDuration(func, arg, &subset, p, &max_rel_mad);
  689. if (total < total_skip) {
  690. ABSL_RAW_LOG(WARNING, "Measurement failed: total %u < %u\n", total,
  691. total_skip);
  692. return 0;
  693. }
  694. const Ticks duration = (total - overhead) - (total_skip - overhead_skip);
  695. results[i].input = unique[i];
  696. results[i].ticks = duration * mul;
  697. results[i].variability = max_rel_mad;
  698. }
  699. return unique.size();
  700. }
  701. size_t Measure(const Func func, const void* arg, const FuncInput* inputs,
  702. const size_t num_inputs, Result* results, const Params& p) {
  703. ABSL_RAW_CHECK(num_inputs != 0, "No inputs");
  704. const InputVec unique = UniqueInputs(inputs, num_inputs);
  705. const size_t num_skip = NumSkip(func, arg, unique, p); // never 0
  706. if (num_skip == 0) return 0; // NumSkip already printed error message
  707. const InputVec full =
  708. ReplicateInputs(inputs, num_inputs, unique.size(), num_skip, p);
  709. // MeasureImpl may fail up to p.max_measure_retries times.
  710. for (size_t i = 0; i < p.max_measure_retries; i++) {
  711. auto result = MeasureImpl(func, arg, num_skip, unique, full, p, results);
  712. if (result != 0) {
  713. return result;
  714. }
  715. }
  716. // All retries failed. (Unusual)
  717. return 0;
  718. }
  719. } // namespace random_internal_nanobenchmark
  720. ABSL_NAMESPACE_END
  721. } // namespace absl