2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/ThreadLocal.h>
19 #include <sys/types.h>
23 #include <condition_variable>
29 #include <boost/thread/tss.hpp>
30 #include <glog/logging.h>
32 #include <folly/Benchmark.h>
33 #include <folly/experimental/io/FsUtil.h>
34 #include <folly/portability/GFlags.h>
36 using namespace folly;
38 // Simple reference implementation using pthread_get_specific
40 class PThreadGetSpecific {
42 PThreadGetSpecific() : key_(0) { pthread_key_create(&key_, OnThreadExit); }
44 T* get() const { return static_cast<T*>(pthread_getspecific(key_)); }
48 pthread_setspecific(key_, t);
50 static void OnThreadExit(void* obj) { delete static_cast<T*>(obj); }
56 DEFINE_int32(numThreads, 8, "Number simultaneous threads for benchmarks.");
59 BENCHMARK(FB_CONCATENATE(BM_mt_, var), iters) { \
60 const int itersPerThread = iters / FLAGS_numThreads; \
61 std::vector<std::thread> threads; \
62 for (int i = 0; i < FLAGS_numThreads; ++i) { \
63 threads.push_back(std::thread([&]() { \
64 var.reset(new int(0)); \
65 for (int j = 0; j < itersPerThread; ++j) { \
70 for (auto& t : threads) { \
75 ThreadLocalPtr<int> tlp;
77 PThreadGetSpecific<int> pthread_get_specific;
78 REG(pthread_get_specific);
79 boost::thread_specific_ptr<int> boost_tsp;
81 BENCHMARK_DRAW_LINE();
83 int main(int argc, char** argv) {
84 gflags::ParseCommandLineFlags(&argc, &argv, true);
85 gflags::SetCommandLineOptionWithMode(
86 "bm_max_iters", "100000000", gflags::SET_FLAG_IF_DEFAULT);
87 folly::runBenchmarks();
92 Ran with 24 threads on dual 12-core Xeon(R) X5650 @ 2.67GHz with 12-MB caches
94 Benchmark Iters Total t t/iter iter/sec
95 ------------------------------------------------------------------------------
96 * BM_mt_tlp 100000000 39.88 ms 398.8 ps 2.335 G
97 +5.91% BM_mt_pthread_get_specific 100000000 42.23 ms 422.3 ps 2.205 G
98 + 295% BM_mt_boost_tsp 100000000 157.8 ms 1.578 ns 604.5 M
99 ------------------------------------------------------------------------------