gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/perf/linux/seqwrite_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 <sys/stat.h>
    18  #include <unistd.h>
    19  
    20  #include "gtest/gtest.h"
    21  #include "benchmark/benchmark.h"
    22  #include "test/util/logging.h"
    23  #include "test/util/temp_path.h"
    24  #include "test/util/test_util.h"
    25  
    26  namespace gvisor {
    27  namespace testing {
    28  
    29  namespace {
    30  
    31  // The maximum file size of the test file, when writes get beyond this point
    32  // they wrap around. This should be large enough to blow away caches.
    33  const uint64_t kMaxFile = 1 << 30;
    34  
    35  // Perform writes of various sizes sequentially to one file. Wraps around if it
    36  // goes above a certain maximum file size.
    37  void BM_SeqWrite(benchmark::State& state) {
    38    auto f = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
    39    FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(f.path(), O_WRONLY));
    40  
    41    const int size = state.range(0);
    42    std::vector<char> buf(size);
    43    RandomizeBuffer(buf.data(), buf.size());
    44  
    45    // Start writes at offset 0.
    46    uint64_t offset = 0;
    47    for (auto _ : state) {
    48      TEST_CHECK(PwriteFd(fd.get(), buf.data(), buf.size(), offset) ==
    49                 ssize_t(buf.size()));
    50      offset += buf.size();
    51      // Wrap around if going above the maximum file size.
    52      if (offset >= kMaxFile) {
    53        offset = 0;
    54      }
    55    }
    56  
    57    state.SetBytesProcessed(static_cast<int64_t>(size) *
    58                            static_cast<int64_t>(state.iterations()));
    59  }
    60  
    61  BENCHMARK(BM_SeqWrite)->Range(1, 1 << 26)->UseRealTime();
    62  
    63  }  // namespace
    64  
    65  }  // namespace testing
    66  }  // namespace gvisor