File: run_and_sleep.cpp

package info (click to toggle)
android-platform-system-extras 10.0.0%2Br36%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 21,588 kB
  • sloc: cpp: 45,171; python: 10,047; ansic: 8,169; sh: 4,029; java: 2,239; javascript: 1,752; xml: 991; asm: 169; makefile: 13
file content (46 lines) | stat: -rw-r--r-- 1,237 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <inttypes.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#define noinline __attribute__((__noinline__))

static inline uint64_t GetSystemClock() {
  timespec ts;
  // Assume clock_gettime() doesn't fail.
  clock_gettime(CLOCK_MONOTONIC, &ts);
  return ts.tv_sec * 1000000000ULL + ts.tv_nsec;
}

constexpr int LOOP_COUNT = 100000000;
uint64_t noinline RunFunction() {
  uint64_t start_time_in_ns = GetSystemClock();
  for (volatile int i = 0; i < LOOP_COUNT; ++i) {
  }
  return GetSystemClock() - start_time_in_ns;
}

uint64_t noinline SleepFunction(unsigned long long sleep_time_in_ns) {
  uint64_t start_time_in_ns = GetSystemClock();
  struct timespec req;
  req.tv_sec = sleep_time_in_ns / 1000000000;
  req.tv_nsec = sleep_time_in_ns % 1000000000;
  nanosleep(&req, nullptr);
  return GetSystemClock() - start_time_in_ns;
}

void noinline GlobalFunction() {
  uint64_t total_sleep_time_in_ns = 0;
  uint64_t total_run_time_in_ns = 0;
  while (true) {
    total_run_time_in_ns += RunFunction();
    if (total_sleep_time_in_ns < total_run_time_in_ns) {
      total_sleep_time_in_ns += SleepFunction(total_run_time_in_ns - total_sleep_time_in_ns);
    }
  }
}

int main() {
  GlobalFunction();
  return 0;
}