github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/perf/linux/open_read_close_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_OpenReadClose(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::CreateFileWith(
    39          GetAbsoluteTestTmpdir(), "some content", 0644));
    40      cache.emplace_back(std::move(path));
    41    }
    42  
    43    char buf[1];
    44    unsigned int seed = 1;
    45    for (auto _ : state) {
    46      const int chosen = rand_r(&seed) % size;
    47      int fd = open(cache[chosen].path().c_str(), O_RDONLY);
    48      TEST_CHECK(fd != -1);
    49      TEST_CHECK(read(fd, buf, 1) == 1);
    50      close(fd);
    51    }
    52  }
    53  
    54  // Gofer dentry cache is 1000 by default. Go over it to force files to be closed
    55  // for real.
    56  BENCHMARK(BM_OpenReadClose)->Range(1000, 16384)->UseRealTime();
    57  
    58  }  // namespace
    59  
    60  }  // namespace testing
    61  }  // namespace gvisor