1/* 2 * Copyright (C) 2014 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 <stdio.h> 18#include <stdio_ext.h> 19#include <stdlib.h> 20 21#include <benchmark/benchmark.h> 22 23#define KB 1024 24#define MB 1024*KB 25 26#define AT_COMMON_SIZES \ 27 Arg(1)->Arg(2)->Arg(3)->Arg(4)->Arg(8)->Arg(16)->Arg(32)->Arg(64)->Arg(512)-> \ 28 Arg(1*KB)->Arg(4*KB)->Arg(8*KB)->Arg(16*KB)->Arg(64*KB) 29 30template <typename Fn> 31void ReadWriteTest(benchmark::State& state, Fn f, bool buffered) { 32 size_t chunk_size = state.range_x(); 33 34 FILE* fp = fopen("/dev/zero", "rw"); 35 __fsetlocking(fp, FSETLOCKING_BYCALLER); 36 char* buf = new char[chunk_size]; 37 38 if (!buffered) { 39 setvbuf(fp, 0, _IONBF, 0); 40 } 41 42 while (state.KeepRunning()) { 43 f(buf, chunk_size, 1, fp); 44 } 45 46 state.SetBytesProcessed(int64_t(state.iterations()) * int64_t(chunk_size)); 47 delete[] buf; 48 fclose(fp); 49} 50 51void BM_stdio_fread(benchmark::State& state) { 52 ReadWriteTest(state, fread, true); 53} 54BENCHMARK(BM_stdio_fread)->AT_COMMON_SIZES; 55 56void BM_stdio_fwrite(benchmark::State& state) { 57 ReadWriteTest(state, fwrite, true); 58} 59BENCHMARK(BM_stdio_fwrite)->AT_COMMON_SIZES; 60 61void BM_stdio_fread_unbuffered(benchmark::State& state) { 62 ReadWriteTest(state, fread, false); 63} 64BENCHMARK(BM_stdio_fread_unbuffered)->AT_COMMON_SIZES; 65 66void BM_stdio_fwrite_unbuffered(benchmark::State& state) { 67 ReadWriteTest(state, fwrite, false); 68} 69BENCHMARK(BM_stdio_fwrite_unbuffered)->AT_COMMON_SIZES; 70 71static void FopenFgetsFclose(benchmark::State& state, bool no_locking) { 72 char buf[1024]; 73 while (state.KeepRunning()) { 74 FILE* fp = fopen("/proc/version", "re"); 75 if (no_locking) __fsetlocking(fp, FSETLOCKING_BYCALLER); 76 if (fgets(buf, sizeof(buf), fp) == nullptr) abort(); 77 fclose(fp); 78 } 79} 80 81static void BM_stdio_fopen_fgets_fclose_locking(benchmark::State& state) { 82 FopenFgetsFclose(state, false); 83} 84BENCHMARK(BM_stdio_fopen_fgets_fclose_locking); 85 86void BM_stdio_fopen_fgets_fclose_no_locking(benchmark::State& state) { 87 FopenFgetsFclose(state, true); 88} 89BENCHMARK(BM_stdio_fopen_fgets_fclose_no_locking); 90