1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <android-base/unique_fd.h>
18 #include <assert.h>
19 #include <err.h>
20 #include <fcntl.h>
21 #include <string.h>
22 #include <time.h>
23 #include <unistd.h>
24
25 #include <algorithm>
26 #include <iomanip>
27 #include <iostream>
28 #include <random>
29
30 using android::base::unique_fd;
31
32 constexpr int kBlockSizeBytes = 4096;
33 constexpr int kNumBytesPerMB = 1024 * 1024;
34
main(int argc,const char * argv[])35 int main(int argc, const char *argv[]) {
36 if (argc != 5 || !(strcmp(argv[3], "rand") == 0 || strcmp(argv[3], "seq") == 0) ||
37 !(strcmp(argv[4], "r") == 0 || strcmp(argv[4], "w") == 0)) {
38 errx(EXIT_FAILURE, "Usage: %s <filename> <file_size_mb> <rand|seq> <r|w>", argv[0]);
39 }
40 int file_size_mb = std::stoi(argv[2]);
41 bool is_rand = (strcmp(argv[3], "rand") == 0);
42 bool is_read = (strcmp(argv[4], "r") == 0);
43 const int block_count = file_size_mb * kNumBytesPerMB / kBlockSizeBytes;
44 std::vector<int> offsets(block_count);
45 for (auto i = 0; i < block_count; ++i) {
46 offsets[i] = i * kBlockSizeBytes;
47 }
48 if (is_rand) {
49 std::mt19937 rd{std::random_device{}()};
50 std::shuffle(offsets.begin(), offsets.end(), rd);
51 }
52 unique_fd fd(open(argv[1], (is_read ? O_RDONLY : O_WRONLY) | O_CLOEXEC));
53 if (fd.get() == -1) {
54 errx(EXIT_FAILURE, "failed to open file: %s", argv[1]);
55 }
56
57 char buf[kBlockSizeBytes];
58 struct timespec start;
59 if (clock_gettime(CLOCK_MONOTONIC, &start) == -1) {
60 err(EXIT_FAILURE, "failed to clock_gettime");
61 }
62 for (auto i = 0; i < block_count; ++i) {
63 auto bytes = is_read ? pread(fd, buf, kBlockSizeBytes, offsets[i])
64 : pwrite(fd, buf, kBlockSizeBytes, offsets[i]);
65 if (bytes == 0) {
66 errx(EXIT_FAILURE, "unexpected end of file");
67 } else if (bytes == -1) {
68 errx(EXIT_FAILURE, "failed to read");
69 }
70 }
71 if (!is_read) {
72 // Writes all the buffered modifications to the open file.
73 assert(syncfs(fd) == 0);
74 }
75 struct timespec finish;
76 if (clock_gettime(CLOCK_MONOTONIC, &finish) == -1) {
77 err(EXIT_FAILURE, "failed to clock_gettime");
78 }
79 double elapsed_seconds = finish.tv_sec - start.tv_sec + (finish.tv_nsec - start.tv_nsec) / 1e9;
80 double rate = (double)file_size_mb / elapsed_seconds;
81 std::cout << std::setprecision(12) << rate << std::endl;
82
83 return EXIT_SUCCESS;
84 }
85