blob: 1162c0fde7373ddabfd20d6bd625c0ec5503c254 [file] [log] [blame]
Daniel Erat73363492019-04-29 23:42:23 -07001// 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.
15const int kSpinNs = 1e8; // 100 ms
16
17// Number of recursive calls to make.
18const int kRecursionDepth = 8;
19
20// Returns the monotonically-increasing time as nanoseconds since the epoch.
21int64_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
47int main() {
48 Recurse(kRecursionDepth);
49 return 0;
50}