github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/perf/linux/sleep_benchmark.cc (about)

     1  // Copyright 2020 The gVisor Authors.
     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  //     http://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  
    15  #include <errno.h>
    16  #include <sys/syscall.h>
    17  #include <time.h>
    18  #include <unistd.h>
    19  
    20  #include "gtest/gtest.h"
    21  #include "benchmark/benchmark.h"
    22  #include "test/util/logging.h"
    23  
    24  namespace gvisor {
    25  namespace testing {
    26  
    27  namespace {
    28  
    29  // Sleep for 'param' nanoseconds.
    30  void BM_Sleep(benchmark::State& state) {
    31    const int nanoseconds = state.range(0);
    32  
    33    for (auto _ : state) {
    34      struct timespec ts;
    35      ts.tv_sec = 0;
    36      ts.tv_nsec = nanoseconds;
    37  
    38      int ret;
    39      do {
    40        ret = syscall(SYS_nanosleep, &ts, &ts);
    41        if (ret < 0) {
    42          TEST_CHECK(errno == EINTR);
    43        }
    44      } while (ret < 0);
    45    }
    46  }
    47  
    48  BENCHMARK(BM_Sleep)
    49      ->Arg(0)
    50      ->Arg(1)
    51      ->Arg(1000)              // 1us
    52      ->Arg(1000 * 1000)       // 1ms
    53      ->Arg(10 * 1000 * 1000)  // 10ms
    54      ->Arg(50 * 1000 * 1000)  // 50ms
    55      ->UseRealTime();
    56  
    57  }  // namespace
    58  
    59  }  // namespace testing
    60  }  // namespace gvisor