Daniel Erat | 7336349 | 2019-04-29 23:42:23 -0700 | [diff] [blame] | 1 | // Copyright 2019 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include <errno.h> |
| 6 | #include <sched.h> |
| 7 | #include <stdint.h> |
| 8 | #include <stdio.h> |
| 9 | #include <stdlib.h> |
| 10 | #include <string.h> |
| 11 | #include <time.h> |
| 12 | #include <unistd.h> |
| 13 | |
| 14 | // Amount of time to spin before returning. |
Daniel Erat | 9b82b68 | 2019-05-05 20:38:56 -0700 | [diff] [blame] | 15 | const int kSpinNs = 1e9; // 1 second |
Daniel Erat | 7336349 | 2019-04-29 23:42:23 -0700 | [diff] [blame] | 16 | |
| 17 | // Number of recursive calls to make. |
| 18 | const int kRecursionDepth = 8; |
| 19 | |
| 20 | // Returns the monotonically-increasing time as nanoseconds since the epoch. |
| 21 | int64_t GetTimeNs() { |
| 22 | struct timespec ts = {0}; |
| 23 | if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { |
| 24 | fprintf(stderr, "clock_gettime: %s", strerror(errno)); |
| 25 | exit(1); |
| 26 | } |
| 27 | return 1e9 * ts.tv_sec + ts.tv_nsec; |
| 28 | } |
| 29 | |
| 30 | // Calls itself n times. The innermost call spins for a short period of time |
| 31 | // before returning. |
| 32 | __attribute__((noinline)) void Recurse(int n) { |
| 33 | if (n > 0) { |
| 34 | Recurse(n-1); |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | const int64_t start = GetTimeNs(); |
| 39 | while (1) { |
| 40 | if (GetTimeNs() - start >= kSpinNs) { |
| 41 | break; |
| 42 | } |
| 43 | sched_yield(); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | int main() { |
| 48 | Recurse(kRecursionDepth); |
| 49 | return 0; |
| 50 | } |