| 6 |
| 7 | #include <memory> |
| 8 | #include <vector> |
| 9 |
| 10 | #include "base/base_switches.h" |
| 11 | #include "base/bind.h" |
| 12 | #include "base/command_line.h" |
| 13 | #include "base/location.h" |
| 14 | #include "base/memory/ptr_util.h" |
| 15 | #include "base/message_loop/message_loop_current.h" |
| 16 | #include "base/single_thread_task_runner.h" |
| 17 | #include "base/strings/stringprintf.h" |
| 18 | #include "base/synchronization/condition_variable.h" |
| 19 | #include "base/synchronization/lock.h" |
| 20 | #include "base/synchronization/waitable_event.h" |
| 21 | #include "base/task/task_observer.h" |
| 22 | #include "base/threading/thread.h" |
| 23 | #include "base/time/time.h" |
| 24 | #include "build/build_config.h" |
| 25 | #include "testing/gtest/include/gtest/gtest.h" |
| 26 | #include "testing/perf/perf_result_reporter.h" |
| 27 |
| 28 | #if defined(OS_POSIX) |
| 29 | #include <pthread.h> |
| 30 | #endif |
| 31 |
| 32 | namespace base { |
| 33 |
| 34 | namespace { |
| 35 |
| 36 | const int kNumRuns = 100000; |
| 37 |
| 38 | constexpr char kMetricPrefixThread[] = "Thread."; |
| 39 | constexpr char kMetricClockTimePerHop[] = "wall_time_per_hop"; |
| 40 | constexpr char kMetricCpuTimePerHop[] = "cpu_time_per_hop"; |
| 41 | constexpr char kStoryBaseTask[] = "task"; |
| 42 | constexpr char kStoryBaseTaskWithObserver[] = "task_with_observer"; |
| 43 | constexpr char kStoryBaseWaitableEvent[] = "waitable_event"; |
| 44 | constexpr char kStoryBaseCondVar[] = "condition_variable"; |
| 45 | constexpr char kStorySuffixOneThread[] = "_1_thread"; |
| 46 | constexpr char kStorySuffixFourThreads[] = "_4_threads"; |
| 47 |
| 48 | #if defined(OS_POSIX) |
| 49 | constexpr char kStoryBasePthreadCondVar[] = "pthread_condition_variable"; |
| 50 | #endif // defined(OS_POSIX) |
| 51 |
| 52 | perf_test::PerfResultReporter SetUpReporter(const std::string& story_name) { |
| 53 | perf_test::PerfResultReporter reporter(kMetricPrefixThread, story_name); |
| 54 | reporter.RegisterImportantMetric(kMetricClockTimePerHop, "us"); |
| 55 | reporter.RegisterImportantMetric(kMetricCpuTimePerHop, "us"); |
| 56 | return reporter; |
| 57 | } |
| 58 |
| 59 | // Base class for a threading perf-test. This sets up some threads for the |
| 60 | // test and measures the clock-time in addition to time spent on each thread. |
| 61 | class ThreadPerfTest : public testing::Test { |
| 62 | public: |
| 63 | ThreadPerfTest() |
| 64 | : done_(WaitableEvent::ResetPolicy::AUTOMATIC, |
| 65 | WaitableEvent::InitialState::NOT_SIGNALED) {} |
| 66 |
| 67 | // To be implemented by each test. Subclass must uses threads_ such that |
| 68 | // their cpu-time can be measured. Test must return from PingPong() _and_ |
| 69 | // call FinishMeasurement from any thread to complete the test. |
| 70 | virtual void Init() { |
| 71 | if (ThreadTicks::IsSupported()) |
| 72 | ThreadTicks::WaitUntilInitialized(); |
| 73 | } |
| 74 | virtual void PingPong(int hops) = 0; |
| 75 | virtual void Reset() {} |
| 76 |
| 77 | void TimeOnThread(base::ThreadTicks* ticks, base::WaitableEvent* done) { |
| 78 | *ticks = base::ThreadTicks::Now(); |
| 79 | done->Signal(); |
| 80 | } |
| 81 |
| 82 | base::ThreadTicks ThreadNow(const base::Thread& thread) { |
| 83 | base::WaitableEvent done(WaitableEvent::ResetPolicy::AUTOMATIC, |
| 84 | WaitableEvent::InitialState::NOT_SIGNALED); |
| 85 | base::ThreadTicks ticks; |
| 86 | thread.task_runner()->PostTask( |
| 87 | FROM_HERE, base::BindOnce(&ThreadPerfTest::TimeOnThread, |
| 88 | base::Unretained(this), &ticks, &done)); |
| 89 | done.Wait(); |
| 90 | return ticks; |
| 91 | } |
| 92 |
| 93 | void RunPingPongTest(const std::string& story_name, unsigned num_threads) { |
| 94 | // Create threads and collect starting cpu-time for each thread. |
| 95 | std::vector<base::ThreadTicks> thread_starts; |
| 96 | while (threads_.size() < num_threads) { |
| 97 | threads_.push_back(std::make_unique<base::Thread>("PingPonger")); |
| 98 | threads_.back()->Start(); |
| 99 | if (base::ThreadTicks::IsSupported()) |
| 100 | thread_starts.push_back(ThreadNow(*threads_.back())); |
| 101 | } |
| 102 |
| 103 | Init(); |
| 104 |
| 105 | base::TimeTicks start = base::TimeTicks::Now(); |
| 106 | PingPong(kNumRuns); |
| 107 | done_.Wait(); |
| 108 | base::TimeTicks end = base::TimeTicks::Now(); |
| 109 |
| 110 | // Gather the cpu-time spent on each thread. This does one extra tasks, |
| 111 | // but that should be in the noise given enough runs. |
| 112 | base::TimeDelta thread_time; |
| 113 | while (threads_.size()) { |
| 114 | if (base::ThreadTicks::IsSupported()) { |
| 115 | thread_time += ThreadNow(*threads_.back()) - thread_starts.back(); |
| 116 | thread_starts.pop_back(); |
| 117 | } |
| 118 | threads_.pop_back(); |
| 119 | } |
| 120 |
| 121 | Reset(); |
| 122 |
| 123 | double num_runs = static_cast<double>(kNumRuns); |
| 124 | double us_per_task_clock = (end - start).InMicroseconds() / num_runs; |
| 125 | double us_per_task_cpu = thread_time.InMicroseconds() / num_runs; |
| 126 |
| 127 | auto reporter = SetUpReporter(story_name); |
| 128 | // Clock time per task. |
| 129 | reporter.AddResult(kMetricClockTimePerHop, us_per_task_clock); |
| 130 |
| 131 | // Total utilization across threads if available (likely higher). |
| 132 | if (base::ThreadTicks::IsSupported()) { |
| 133 | reporter.AddResult(kMetricCpuTimePerHop, us_per_task_cpu); |
| 134 | } |
| 135 | } |
| 136 |
| 137 | protected: |
| 138 | void FinishMeasurement() { done_.Signal(); } |
| 139 | std::vector<std::unique_ptr<base::Thread>> threads_; |
| 140 |
| 141 | private: |
| 142 | base::WaitableEvent done_; |
| 143 | }; |
| 144 |
| 145 | // Class to test task performance by posting empty tasks back and forth. |
| 146 | class TaskPerfTest : public ThreadPerfTest { |
| 147 | base::Thread* NextThread(int count) { |
| 148 | return threads_[count % threads_.size()].get(); |
| 149 | } |
| 150 |
| 151 | void PingPong(int hops) override { |
| 152 | if (!hops) { |
| 153 | FinishMeasurement(); |
| 154 | return; |
| 155 | } |
| 156 | NextThread(hops)->task_runner()->PostTask( |
| 157 | FROM_HERE, base::BindOnce(&ThreadPerfTest::PingPong, |
| 158 | base::Unretained(this), hops - 1)); |
| 159 | } |
| 160 | }; |
| 161 |
| 162 | // This tries to test the 'best-case' as well as the 'worst-case' task posting |
| 163 | // performance. The best-case keeps one thread alive such that it never yeilds, |
| 164 | // while the worse-case forces a context switch for every task. Four threads are |
| 165 | // used to ensure the threads do yeild (with just two it might be possible for |
| 166 | // both threads to stay awake if they can signal each other fast enough). |
| 167 | TEST_F(TaskPerfTest, TaskPingPong) { |
| 168 | RunPingPongTest(std::string(kStoryBaseTask) + kStorySuffixOneThread, 1); |
| 169 | RunPingPongTest(std::string(kStoryBaseTask) + kStorySuffixFourThreads, 4); |
| 170 | } |
| 171 |
| 172 |
| 173 | // Same as above, but add observers to test their perf impact. |
| 174 | class MessageLoopObserver : public base::TaskObserver { |
| 175 | public: |
| 176 | void WillProcessTask(const base::PendingTask& pending_task, |
| 177 | bool was_blocked_or_low_priority) override {} |
| 178 | void DidProcessTask(const base::PendingTask& pending_task) override {} |
| 179 | }; |
| 180 | MessageLoopObserver message_loop_observer; |
| 181 |
| 182 | class TaskObserverPerfTest : public TaskPerfTest { |
| 183 | public: |
| 184 | void Init() override { |
| 185 | TaskPerfTest::Init(); |
| 186 | for (auto& i : threads_) { |
| 187 | i->task_runner()->PostTask( |
| 188 | FROM_HERE, BindOnce( |
| 189 | [](MessageLoopObserver* observer) { |
| 190 | MessageLoopCurrent::Get()->AddTaskObserver(observer); |
| 191 | }, |
| 192 | Unretained(&message_loop_observer))); |
| 193 | } |
| 194 | } |
| 195 | }; |
| 196 |
| 197 | TEST_F(TaskObserverPerfTest, TaskPingPong) { |
| 198 | RunPingPongTest( |
| 199 | std::string(kStoryBaseTaskWithObserver) + kStorySuffixOneThread, 1); |
| 200 | RunPingPongTest( |
| 201 | std::string(kStoryBaseTaskWithObserver) + kStorySuffixFourThreads, 4); |
| 202 | } |
| 203 |
| 204 | // Class to test our WaitableEvent performance by signaling back and fort. |
| 205 | // WaitableEvent is templated so we can also compare with other versions. |
| 206 | template <typename WaitableEventType> |
| 207 | class EventPerfTest : public ThreadPerfTest { |
| 208 | public: |
| 209 | void Init() override { |
| 210 | for (size_t i = 0; i < threads_.size(); i++) { |
| 211 | events_.push_back(std::make_unique<WaitableEventType>( |
| 212 | WaitableEvent::ResetPolicy::AUTOMATIC, |
| 213 | WaitableEvent::InitialState::NOT_SIGNALED)); |
| 214 | } |
| 215 | } |
| 216 |
| 217 | void Reset() override { events_.clear(); } |
| 218 |
| 219 | void WaitAndSignalOnThread(size_t event) { |
| 220 | size_t next_event = (event + 1) % events_.size(); |
| 221 | int my_hops = 0; |
| 222 | do { |
| 223 | events_[event]->Wait(); |
| 224 | my_hops = --remaining_hops_; // We own 'hops' between Wait and Signal. |
| 225 | events_[next_event]->Signal(); |
| 226 | } while (my_hops > 0); |
| 227 | // Once we are done, all threads will signal as hops passes zero. |
| 228 | // We only signal completion once, on the thread that reaches zero. |
| 229 | if (!my_hops) |
| 230 | FinishMeasurement(); |
| 231 | } |
| 232 |
| 233 | void PingPong(int hops) override { |
| 234 | remaining_hops_ = hops; |
| 235 | for (size_t i = 0; i < threads_.size(); i++) { |
| 236 | threads_[i]->task_runner()->PostTask( |
| 237 | FROM_HERE, base::BindOnce(&EventPerfTest::WaitAndSignalOnThread, |
| 238 | base::Unretained(this), i)); |
| 239 | } |
| 240 |
| 241 | // Kick off the Signal ping-ponging. |
| 242 | events_.front()->Signal(); |
| 243 | } |
| 244 |
| 245 | int remaining_hops_; |
| 246 | std::vector<std::unique_ptr<WaitableEventType>> events_; |
| 247 | }; |
| 248 |
| 249 | // Similar to the task posting test, this just tests similar functionality |
| 250 | // using WaitableEvents. We only test four threads (worst-case), but we |
| 251 | // might want to craft a way to test the best-case (where the thread doesn't |
| 252 | // end up blocking because the event is already signalled). |
| 253 | typedef EventPerfTest<base::WaitableEvent> WaitableEventThreadPerfTest; |
| 254 | TEST_F(WaitableEventThreadPerfTest, EventPingPong) { |
| 255 | RunPingPongTest( |
| 256 | std::string(kStoryBaseWaitableEvent) + kStorySuffixFourThreads, 4); |
| 257 | } |
| 258 |
| 259 | // Build a minimal event using ConditionVariable. |
| 260 | class ConditionVariableEvent { |
| 261 | public: |
| 262 | ConditionVariableEvent(WaitableEvent::ResetPolicy reset_policy, |
| 263 | WaitableEvent::InitialState initial_state) |
| 264 | : cond_(&lock_), signaled_(false) { |
| 265 | DCHECK_EQ(WaitableEvent::ResetPolicy::AUTOMATIC, reset_policy); |
| 266 | DCHECK_EQ(WaitableEvent::InitialState::NOT_SIGNALED, initial_state); |
| 267 | } |
| 268 |
| 269 | void Signal() { |
| 270 | { |
| 271 | base::AutoLock scoped_lock(lock_); |
| 272 | signaled_ = true; |
| 273 | } |
| 274 | cond_.Signal(); |
| 275 | } |
| 276 |
| 277 | void Wait() { |
| 278 | base::AutoLock scoped_lock(lock_); |
| 279 | while (!signaled_) |
| 280 | cond_.Wait(); |
| 281 | signaled_ = false; |
| 282 | } |
| 283 |
| 284 | private: |
| 285 | base::Lock lock_; |
| 286 | base::ConditionVariable cond_; |
| 287 | bool signaled_; |
| 288 | }; |
| 289 |
| 290 | // This is meant to test the absolute minimal context switching time |
| 291 | // using our own base synchronization code. |
| 292 | typedef EventPerfTest<ConditionVariableEvent> ConditionVariablePerfTest; |
| 293 | TEST_F(ConditionVariablePerfTest, EventPingPong) { |
| 294 | RunPingPongTest(std::string(kStoryBaseCondVar) + kStorySuffixFourThreads, 4); |
| 295 | } |
| 296 | #if defined(OS_POSIX) |
| 297 |
| 298 | // Absolutely 100% minimal posix waitable event. If there is a better/faster |
| 299 | // way to force a context switch, we should use that instead. |
| 300 | class PthreadEvent { |
| 301 | public: |
| 302 | PthreadEvent(WaitableEvent::ResetPolicy reset_policy, |
| 303 | WaitableEvent::InitialState initial_state) { |
| 304 | DCHECK_EQ(WaitableEvent::ResetPolicy::AUTOMATIC, reset_policy); |
| 305 | DCHECK_EQ(WaitableEvent::InitialState::NOT_SIGNALED, initial_state); |
| 306 | pthread_mutex_init(&mutex_, nullptr); |
| 307 | pthread_cond_init(&cond_, nullptr); |
| 308 | signaled_ = false; |
| 309 | } |
| 310 |
| 311 | ~PthreadEvent() { |
| 312 | pthread_cond_destroy(&cond_); |
| 313 | pthread_mutex_destroy(&mutex_); |
| 314 | } |
| 315 |
| 316 | void Signal() { |
| 317 | pthread_mutex_lock(&mutex_); |
| 318 | signaled_ = true; |
| 319 | pthread_mutex_unlock(&mutex_); |
| 320 | pthread_cond_signal(&cond_); |
| 321 | } |
| 322 |
| 323 | void Wait() { |
| 324 | pthread_mutex_lock(&mutex_); |
| 325 | while (!signaled_) |
| 326 | pthread_cond_wait(&cond_, &mutex_); |
| 327 | signaled_ = false; |
| 328 | pthread_mutex_unlock(&mutex_); |
| 329 | } |
| 330 |
| 331 | private: |
| 332 | bool signaled_; |
| 333 | pthread_mutex_t mutex_; |
| 334 | pthread_cond_t cond_; |
| 335 | }; |
| 336 |
| 337 | // This is meant to test the absolute minimal context switching time. |
| 338 | // If there is any faster way to do this we should substitute it in. |
| 339 | typedef EventPerfTest<PthreadEvent> PthreadEventPerfTest; |
| 340 | TEST_F(PthreadEventPerfTest, EventPingPong) { |
| 341 | RunPingPongTest( |
| 342 | std::string(kStoryBasePthreadCondVar) + kStorySuffixFourThreads, 4); |
| 343 | } |
| 344 |
| 345 | #endif |
| 346 |
| 347 | } // namespace |
| 348 |
| 349 | } // namespace base |
| 350 |