Roll src/third_party/skia d32087a:1052f51
[chromium-blink-merge.git] / base / profiler / stack_sampling_profiler.cc
bloba197d844093d13cd08c447a6748d426499d713bc
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/profiler/stack_sampling_profiler.h"
7 #include <algorithm>
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/callback.h"
12 #include "base/lazy_instance.h"
13 #include "base/location.h"
14 #include "base/profiler/native_stack_sampler.h"
15 #include "base/synchronization/lock.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/timer/elapsed_timer.h"
19 namespace base {
21 namespace {
23 // Used to ensure only one profiler is running at a time.
24 LazyInstance<Lock> concurrent_profiling_lock = LAZY_INSTANCE_INITIALIZER;
26 // AsyncRunner ----------------------------------------------------------------
28 // Helper class to allow a profiler to be run completely asynchronously from the
29 // initiator, without being concerned with the profiler's lifetime.
30 class AsyncRunner {
31 public:
32 // Sets up a profiler and arranges for it to be deleted on its completed
33 // callback.
34 static void Run(PlatformThreadId thread_id,
35 const StackSamplingProfiler::SamplingParams& params,
36 const StackSamplingProfiler::CompletedCallback& callback);
38 private:
39 AsyncRunner();
41 // Runs the callback and deletes the AsyncRunner instance.
42 static void RunCallbackAndDeleteInstance(
43 scoped_ptr<AsyncRunner> object_to_be_deleted,
44 const StackSamplingProfiler::CompletedCallback& callback,
45 scoped_refptr<SingleThreadTaskRunner> task_runner,
46 const StackSamplingProfiler::CallStackProfiles& profiles);
48 scoped_ptr<StackSamplingProfiler> profiler_;
50 DISALLOW_COPY_AND_ASSIGN(AsyncRunner);
53 // static
54 void AsyncRunner::Run(
55 PlatformThreadId thread_id,
56 const StackSamplingProfiler::SamplingParams& params,
57 const StackSamplingProfiler::CompletedCallback &callback) {
58 scoped_ptr<AsyncRunner> runner(new AsyncRunner);
59 AsyncRunner* temp_ptr = runner.get();
60 temp_ptr->profiler_.reset(
61 new StackSamplingProfiler(thread_id, params,
62 Bind(&AsyncRunner::RunCallbackAndDeleteInstance,
63 Passed(&runner), callback,
64 ThreadTaskRunnerHandle::Get())));
65 // The callback won't be called until after Start(), so temp_ptr will still
66 // be valid here.
67 temp_ptr->profiler_->Start();
70 AsyncRunner::AsyncRunner() {}
72 void AsyncRunner::RunCallbackAndDeleteInstance(
73 scoped_ptr<AsyncRunner> object_to_be_deleted,
74 const StackSamplingProfiler::CompletedCallback& callback,
75 scoped_refptr<SingleThreadTaskRunner> task_runner,
76 const StackSamplingProfiler::CallStackProfiles& profiles) {
77 callback.Run(profiles);
78 // Delete the instance on the original calling thread.
79 task_runner->DeleteSoon(FROM_HERE, object_to_be_deleted.release());
82 } // namespace
84 // StackSamplingProfiler::Module ----------------------------------------------
86 StackSamplingProfiler::Module::Module() : base_address(0u) {}
87 StackSamplingProfiler::Module::Module(uintptr_t base_address,
88 const std::string& id,
89 const FilePath& filename)
90 : base_address(base_address), id(id), filename(filename) {}
92 StackSamplingProfiler::Module::~Module() {}
94 // StackSamplingProfiler::Frame -----------------------------------------------
96 StackSamplingProfiler::Frame::Frame(uintptr_t instruction_pointer,
97 size_t module_index)
98 : instruction_pointer(instruction_pointer), module_index(module_index) {}
100 StackSamplingProfiler::Frame::~Frame() {}
102 StackSamplingProfiler::Frame::Frame() {}
104 // StackSamplingProfiler::CallStackProfile ------------------------------------
106 StackSamplingProfiler::CallStackProfile::CallStackProfile() {}
108 StackSamplingProfiler::CallStackProfile::~CallStackProfile() {}
110 // StackSamplingProfiler::SamplingThread --------------------------------------
112 StackSamplingProfiler::SamplingThread::SamplingThread(
113 scoped_ptr<NativeStackSampler> native_sampler,
114 const SamplingParams& params,
115 const CompletedCallback& completed_callback)
116 : native_sampler_(native_sampler.Pass()),
117 params_(params),
118 stop_event_(false, false),
119 completed_callback_(completed_callback) {
122 StackSamplingProfiler::SamplingThread::~SamplingThread() {}
124 void StackSamplingProfiler::SamplingThread::ThreadMain() {
125 PlatformThread::SetName("Chrome_SamplingProfilerThread");
127 // For now, just ignore any requests to profile while another profiler is
128 // working.
129 if (!concurrent_profiling_lock.Get().Try())
130 return;
132 CallStackProfiles profiles;
133 CollectProfiles(&profiles);
134 concurrent_profiling_lock.Get().Release();
135 completed_callback_.Run(profiles);
138 // Depending on how long the sampling takes and the length of the sampling
139 // interval, a burst of samples could take arbitrarily longer than
140 // samples_per_burst * sampling_interval. In this case, we (somewhat
141 // arbitrarily) honor the number of samples requested rather than strictly
142 // adhering to the sampling intervals. Once we have established users for the
143 // StackSamplingProfiler and the collected data to judge, we may go the other
144 // way or make this behavior configurable.
145 void StackSamplingProfiler::SamplingThread::CollectProfile(
146 CallStackProfile* profile,
147 TimeDelta* elapsed_time,
148 bool* was_stopped) {
149 ElapsedTimer profile_timer;
150 native_sampler_->ProfileRecordingStarting(&profile->modules);
151 profile->sampling_period = params_.sampling_interval;
152 *was_stopped = false;
153 TimeDelta previous_elapsed_sample_time;
154 for (int i = 0; i < params_.samples_per_burst; ++i) {
155 if (i != 0) {
156 // Always wait, even if for 0 seconds, so we can observe a signal on
157 // stop_event_.
158 if (stop_event_.TimedWait(
159 std::max(params_.sampling_interval - previous_elapsed_sample_time,
160 TimeDelta()))) {
161 *was_stopped = true;
162 break;
165 ElapsedTimer sample_timer;
166 profile->samples.push_back(Sample());
167 native_sampler_->RecordStackSample(&profile->samples.back());
168 previous_elapsed_sample_time = sample_timer.Elapsed();
171 *elapsed_time = profile_timer.Elapsed();
172 profile->profile_duration = *elapsed_time;
173 native_sampler_->ProfileRecordingStopped();
176 // In an analogous manner to CollectProfile() and samples exceeding the expected
177 // total sampling time, bursts may also exceed the burst_interval. We adopt the
178 // same wait-and-see approach here.
179 void StackSamplingProfiler::SamplingThread::CollectProfiles(
180 CallStackProfiles* profiles) {
181 if (stop_event_.TimedWait(params_.initial_delay))
182 return;
184 TimeDelta previous_elapsed_profile_time;
185 for (int i = 0; i < params_.bursts; ++i) {
186 if (i != 0) {
187 // Always wait, even if for 0 seconds, so we can observe a signal on
188 // stop_event_.
189 if (stop_event_.TimedWait(
190 std::max(params_.burst_interval - previous_elapsed_profile_time,
191 TimeDelta())))
192 return;
195 CallStackProfile profile;
196 bool was_stopped = false;
197 CollectProfile(&profile, &previous_elapsed_profile_time, &was_stopped);
198 if (!profile.samples.empty())
199 profiles->push_back(profile);
201 if (was_stopped)
202 return;
206 void StackSamplingProfiler::SamplingThread::Stop() {
207 stop_event_.Signal();
210 // StackSamplingProfiler ------------------------------------------------------
212 StackSamplingProfiler::SamplingParams::SamplingParams()
213 : initial_delay(TimeDelta::FromMilliseconds(0)),
214 bursts(1),
215 burst_interval(TimeDelta::FromMilliseconds(10000)),
216 samples_per_burst(300),
217 sampling_interval(TimeDelta::FromMilliseconds(100)) {
220 StackSamplingProfiler::StackSamplingProfiler(PlatformThreadId thread_id,
221 const SamplingParams& params,
222 const CompletedCallback& callback)
223 : thread_id_(thread_id), params_(params), completed_callback_(callback) {}
225 StackSamplingProfiler::~StackSamplingProfiler() {
226 Stop();
227 if (!sampling_thread_handle_.is_null())
228 PlatformThread::Join(sampling_thread_handle_);
231 // static
232 void StackSamplingProfiler::StartAndRunAsync(
233 PlatformThreadId thread_id,
234 const SamplingParams& params,
235 const CompletedCallback& callback) {
236 CHECK(ThreadTaskRunnerHandle::Get());
237 AsyncRunner::Run(thread_id, params, callback);
240 void StackSamplingProfiler::Start() {
241 if (completed_callback_.is_null())
242 return;
244 scoped_ptr<NativeStackSampler> native_sampler =
245 NativeStackSampler::Create(thread_id_);
246 if (!native_sampler)
247 return;
249 sampling_thread_.reset(
250 new SamplingThread(native_sampler.Pass(), params_, completed_callback_));
251 if (!PlatformThread::Create(0, sampling_thread_.get(),
252 &sampling_thread_handle_))
253 sampling_thread_.reset();
256 void StackSamplingProfiler::Stop() {
257 if (sampling_thread_)
258 sampling_thread_->Stop();
261 // StackSamplingProfiler::Frame global functions ------------------------------
263 bool operator==(const StackSamplingProfiler::Frame &a,
264 const StackSamplingProfiler::Frame &b) {
265 return a.instruction_pointer == b.instruction_pointer &&
266 a.module_index == b.module_index;
269 bool operator<(const StackSamplingProfiler::Frame &a,
270 const StackSamplingProfiler::Frame &b) {
271 return (a.module_index < b.module_index) ||
272 (a.module_index == b.module_index &&
273 a.instruction_pointer < b.instruction_pointer);
276 } // namespace base