github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/perf/linux/open_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 <fcntl.h>
    16  #include <stdlib.h>
    17  #include <unistd.h>
    18  
    19  #include <memory>
    20  #include <string>
    21  #include <vector>
    22  
    23  #include "gtest/gtest.h"
    24  #include "benchmark/benchmark.h"
    25  #include "test/util/fs_util.h"
    26  #include "test/util/logging.h"
    27  #include "test/util/temp_path.h"
    28  
    29  namespace gvisor {
    30  namespace testing {
    31  
    32  namespace {
    33  
    34  void BM_Open(benchmark::State& state) {
    35    const int size = state.range(0);
    36    std::vector<TempPath> cache;
    37    for (int i = 0; i < size; i++) {
    38      auto path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
    39      cache.emplace_back(std::move(path));
    40    }
    41  
    42    unsigned int seed = 1;
    43    for (auto _ : state) {
    44      const int chosen = rand_r(&seed) % size;
    45      int fd = open(cache[chosen].path().c_str(), O_RDONLY);
    46      TEST_CHECK(fd != -1);
    47      close(fd);
    48    }
    49  }
    50  
    51  BENCHMARK(BM_Open)->Range(1, 128)->UseRealTime();
    52  
    53  }  // namespace
    54  
    55  }  // namespace testing
    56  }  // namespace gvisor