tracing-cpu-profiler.cc 2.63 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/profiler/tracing-cpu-profiler.h"

7 8
#include "src/profiler/cpu-profiler.h"
#include "src/tracing/trace-event.h"
9 10 11 12 13 14
#include "src/v8.h"

namespace v8 {

std::unique_ptr<TracingCpuProfiler> TracingCpuProfiler::Create(
    v8::Isolate* isolate) {
15 16 17 18
  // Dummy profiler that does nothing.
  // Remove it along with the deprecated code.
  // The actual profiler is created by the isolate itself.
  return std::unique_ptr<TracingCpuProfiler>(new TracingCpuProfiler());
19 20 21 22
}

namespace internal {

23 24 25
TracingCpuProfilerImpl::TracingCpuProfilerImpl(Isolate* isolate)
    : isolate_(isolate), profiling_enabled_(false) {
  // Make sure tracing system notices profiler categories.
26 27 28
  TRACE_EVENT_WARMUP_CATEGORY(TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler"));
  TRACE_EVENT_WARMUP_CATEGORY(
      TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler.hires"));
29
  V8::GetCurrentPlatform()->GetTracingController()->AddTraceStateObserver(this);
30 31 32 33
}

TracingCpuProfilerImpl::~TracingCpuProfilerImpl() {
  StopProfiling();
34 35
  V8::GetCurrentPlatform()->GetTracingController()->RemoveTraceStateObserver(
      this);
36 37 38
}

void TracingCpuProfilerImpl::OnTraceEnabled() {
39 40 41 42
  bool enabled;
  TRACE_EVENT_CATEGORY_GROUP_ENABLED(
      TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler"), &enabled);
  if (!enabled) return;
43 44 45 46 47 48 49
  profiling_enabled_ = true;
  isolate_->RequestInterrupt(
      [](v8::Isolate*, void* data) {
        reinterpret_cast<TracingCpuProfilerImpl*>(data)->StartProfiling();
      },
      this);
}
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64
void TracingCpuProfilerImpl::OnTraceDisabled() {
  base::LockGuard<base::Mutex> lock(&mutex_);
  if (!profiling_enabled_) return;
  profiling_enabled_ = false;
  isolate_->RequestInterrupt(
      [](v8::Isolate*, void* data) {
        reinterpret_cast<TracingCpuProfilerImpl*>(data)->StopProfiling();
      },
      this);
}

void TracingCpuProfilerImpl::StartProfiling() {
  base::LockGuard<base::Mutex> lock(&mutex_);
  if (!profiling_enabled_ || profiler_) return;
65 66 67 68
  bool enabled;
  TRACE_EVENT_CATEGORY_GROUP_ENABLED(
      TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler.hires"), &enabled);
  int sampling_interval_us = enabled ? 100 : 1000;
69 70 71 72 73 74 75 76 77 78 79 80
  profiler_.reset(new CpuProfiler(isolate_));
  profiler_->set_sampling_interval(
      base::TimeDelta::FromMicroseconds(sampling_interval_us));
  profiler_->StartProfiling("", true);
}

void TracingCpuProfilerImpl::StopProfiling() {
  base::LockGuard<base::Mutex> lock(&mutex_);
  if (!profiler_) return;
  profiler_->StopProfiling("");
  profiler_.reset();
}
81 82 83

}  // namespace internal
}  // namespace v8