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 <errno.h>
18 #include <string.h>
19 #include <sys/syscall.h>
20 #include <sys/types.h>
21 #include <sys/wait.h>
22 #include <unistd.h>
23
24 #include <string>
25
26 #include <android-base/stringprintf.h>
27 #include <benchmark/benchmark.h>
28 #include "util.h"
29
30 BIONIC_TRIVIAL_BENCHMARK(BM_unistd_getpid, getpid());
31 BIONIC_TRIVIAL_BENCHMARK(BM_unistd_getpid_syscall, syscall(__NR_getpid));
32
33 // TODO: glibc 2.30 added gettid() too.
34 #if defined(__BIONIC__)
35 BIONIC_TRIVIAL_BENCHMARK(BM_unistd_gettid, gettid());
36 #endif
37 BIONIC_TRIVIAL_BENCHMARK(BM_unistd_gettid_syscall, syscall(__NR_gettid));
38
39 // Many native allocators have custom prefork and postfork functions.
40 // Measure the fork call to make sure nothing takes too long.
BM_unistd_fork_call(benchmark::State & state)41 void BM_unistd_fork_call(benchmark::State& state) {
42 for (auto _ : state) {
43 pid_t pid;
44 if ((pid = fork()) == 0) {
45 // Sleep for a little while so that the parent is not interrupted
46 // right away when the process exits.
47 usleep(100);
48 _exit(1);
49 }
50 state.PauseTiming();
51 if (pid == -1) {
52 std::string err = android::base::StringPrintf("Fork failed: %s", strerror(errno));
53 state.SkipWithError(err.c_str());
54 }
55 pid_t wait_pid = waitpid(pid, 0, 0);
56 if (wait_pid != pid) {
57 if (wait_pid == -1) {
58 std::string err = android::base::StringPrintf("waitpid call failed: %s", strerror(errno));
59 state.SkipWithError(err.c_str());
60 } else {
61 std::string err = android::base::StringPrintf(
62 "waitpid return an unknown pid, expected %d, actual %d", pid, wait_pid);
63 state.SkipWithError(err.c_str());
64 }
65 }
66 state.ResumeTiming();
67 }
68 }
69 BIONIC_BENCHMARK(BM_unistd_fork_call);
70