counters.cc 18.1 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/logging/counters.h"
6

7 8
#include <iomanip>

9
#include "src/base/platform/platform.h"
10
#include "src/builtins/builtins-definitions.h"
11
#include "src/execution/isolate.h"
12 13 14
#include "src/logging/counters-inl.h"
#include "src/logging/log-inl.h"
#include "src/logging/log.h"
15
#include "src/utils/ostreams.h"
16

17 18
namespace v8 {
namespace internal {
19

20
std::atomic_uint TracingFlags::runtime_stats{0};
21
std::atomic_uint TracingFlags::gc{0};
22 23 24
std::atomic_uint TracingFlags::gc_stats{0};
std::atomic_uint TracingFlags::ic_stats{0};

25
StatsTable::StatsTable(Counters* counters)
26 27 28
    : lookup_function_(nullptr),
      create_histogram_function_(nullptr),
      add_histogram_sample_function_(nullptr) {}
29

30
void StatsTable::SetCounterFunction(CounterLookupCallback f) {
31 32
  lookup_function_ = f;
}
33

34
int* StatsCounterBase::FindLocationInStatsTable() const {
35
  return counters_->FindLocation(name_);
36 37
}

38
StatsCounterThreadSafe::StatsCounterThreadSafe(Counters* counters,
39
                                               const char* name)
40
    : StatsCounterBase(counters, name) {}
41 42 43

void StatsCounterThreadSafe::Set(int Value) {
  if (ptr_) {
44
    base::MutexGuard Guard(&mutex_);
45 46 47 48 49 50
    SetLoc(ptr_, Value);
  }
}

void StatsCounterThreadSafe::Increment() {
  if (ptr_) {
51
    base::MutexGuard Guard(&mutex_);
52 53 54 55 56 57
    IncrementLoc(ptr_);
  }
}

void StatsCounterThreadSafe::Increment(int value) {
  if (ptr_) {
58
    base::MutexGuard Guard(&mutex_);
59 60 61 62 63 64
    IncrementLoc(ptr_, value);
  }
}

void StatsCounterThreadSafe::Decrement() {
  if (ptr_) {
65
    base::MutexGuard Guard(&mutex_);
66 67 68 69 70 71
    DecrementLoc(ptr_);
  }
}

void StatsCounterThreadSafe::Decrement(int value) {
  if (ptr_) {
72
    base::MutexGuard Guard(&mutex_);
73 74 75 76
    DecrementLoc(ptr_, value);
  }
}

77 78
void Histogram::AddSample(int sample) {
  if (Enabled()) {
79
    counters_->AddHistogramSample(histogram_, sample);
80 81 82 83
  }
}

void* Histogram::CreateHistogram() const {
84
  return counters_->CreateHistogram(name_, min_, max_, num_buckets_);
85 86
}

87 88 89
void TimedHistogram::Start(base::ElapsedTimer* timer, Isolate* isolate) {
  if (Enabled()) timer->Start();
  if (isolate) Logger::CallEventLogger(isolate, name(), Logger::START, true);
90 91
}

92
void TimedHistogram::Stop(base::ElapsedTimer* timer, Isolate* isolate) {
93
  if (Enabled()) {
94 95 96 97
    int64_t sample = resolution_ == HistogramTimerResolution::MICROSECOND
                         ? timer->Elapsed().InMicroseconds()
                         : timer->Elapsed().InMilliseconds();
    timer->Stop();
yangguo's avatar
yangguo committed
98
    AddSample(static_cast<int>(sample));
99
  }
100 101 102
  if (isolate != nullptr) {
    Logger::CallEventLogger(isolate, name(), Logger::END, true);
  }
103 104
}

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
void TimedHistogram::RecordAbandon(base::ElapsedTimer* timer,
                                   Isolate* isolate) {
  if (Enabled()) {
    DCHECK(timer->IsStarted());
    timer->Stop();
    int64_t sample = resolution_ == HistogramTimerResolution::MICROSECOND
                         ? base::TimeDelta::Max().InMicroseconds()
                         : base::TimeDelta::Max().InMilliseconds();
    AddSample(static_cast<int>(sample));
  }
  if (isolate != nullptr) {
    Logger::CallEventLogger(isolate, name(), Logger::END, true);
  }
}

120
Counters::Counters(Isolate* isolate)
121 122
    : isolate_(isolate),
      stats_table_(this),
123
// clang format off
124
#define SC(name, caption) name##_(this, "c:" #caption),
125 126 127
      STATS_COUNTER_TS_LIST(SC)
#undef SC
      // clang format on
128 129
      runtime_call_stats_(),
      worker_thread_runtime_call_stats_() {
130 131 132 133 134 135 136
  static const struct {
    Histogram Counters::*member;
    const char* caption;
    int min;
    int max;
    int num_buckets;
  } kHistograms[] = {
137
#define HR(name, caption, min, max, num_buckets) \
138 139
  {&Counters::name##_, #caption, min, max, num_buckets},
      HISTOGRAM_RANGE_LIST(HR)
140
#undef HR
141 142 143 144
  };
  for (const auto& histogram : kHistograms) {
    this->*histogram.member =
        Histogram(histogram.caption, histogram.min, histogram.max,
145
                  histogram.num_buckets, this);
146
  }
147

148 149
  const int DefaultTimedHistogramNumBuckets = 50;

150 151 152 153
  static const struct {
    HistogramTimer Counters::*member;
    const char* caption;
    int max;
154
    HistogramTimerResolution res;
155
  } kHistogramTimers[] = {
yangguo's avatar
yangguo committed
156
#define HT(name, caption, max, res) \
157
  {&Counters::name##_, #caption, max, HistogramTimerResolution::res},
158
      HISTOGRAM_TIMER_LIST(HT)
159
#undef HT
160 161
  };
  for (const auto& timer : kHistogramTimers) {
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    this->*timer.member = HistogramTimer(timer.caption, 0, timer.max, timer.res,
                                         DefaultTimedHistogramNumBuckets, this);
  }

  static const struct {
    TimedHistogram Counters::*member;
    const char* caption;
    int max;
    HistogramTimerResolution res;
  } kTimedHistograms[] = {
#define HT(name, caption, max, res) \
  {&Counters::name##_, #caption, max, HistogramTimerResolution::res},
      TIMED_HISTOGRAM_LIST(HT)
#undef HT
  };
  for (const auto& timer : kTimedHistograms) {
    this->*timer.member = TimedHistogram(timer.caption, 0, timer.max, timer.res,
                                         DefaultTimedHistogramNumBuckets, this);
180
  }
181

182 183 184 185 186 187
  static const struct {
    AggregatableHistogramTimer Counters::*member;
    const char* caption;
  } kAggregatableHistogramTimers[] = {
#define AHT(name, caption) {&Counters::name##_, #caption},
      AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
188
#undef AHT
189 190
  };
  for (const auto& aht : kAggregatableHistogramTimers) {
191 192
    this->*aht.member = AggregatableHistogramTimer(
        aht.caption, 0, 10000000, DefaultTimedHistogramNumBuckets, this);
193
  }
194

195 196 197 198 199 200
  static const struct {
    Histogram Counters::*member;
    const char* caption;
  } kHistogramPercentages[] = {
#define HP(name, caption) {&Counters::name##_, #caption},
      HISTOGRAM_PERCENTAGE_LIST(HP)
201
#undef HP
202 203
  };
  for (const auto& percentage : kHistogramPercentages) {
204
    this->*percentage.member = Histogram(percentage.caption, 0, 101, 100, this);
205
  }
206

207 208 209 210 211 212 213 214 215 216 217 218
  // Exponential histogram assigns bucket limits to points
  // p[1], p[2], ... p[n] such that p[i+1] / p[i] = constant.
  // The constant factor is equal to the n-th root of (high / low),
  // where the n is the number of buckets, the low is the lower limit,
  // the high is the upper limit.
  // For n = 50, low = 1000, high = 500000: the factor = 1.13.
  static const struct {
    Histogram Counters::*member;
    const char* caption;
  } kLegacyMemoryHistograms[] = {
#define HM(name, caption) {&Counters::name##_, #caption},
      HISTOGRAM_LEGACY_MEMORY_LIST(HM)
219
#undef HM
220 221 222
  };
  for (const auto& histogram : kLegacyMemoryHistograms) {
    this->*histogram.member =
223
        Histogram(histogram.caption, 1000, 500000, 50, this);
224
  }
225

226 227 228 229 230 231
  // clang-format off
  static const struct {
    StatsCounter Counters::*member;
    const char* caption;
  } kStatsCounters[] = {
#define SC(name, caption) {&Counters::name##_, "c:" #caption},
232 233 234
  STATS_COUNTER_LIST_1(SC)
  STATS_COUNTER_LIST_2(SC)
  STATS_COUNTER_NATIVE_CODE_LIST(SC)
235
#undef SC
236 237 238 239
#define SC(name)                                             \
  {&Counters::count_of_##name##_, "c:" "V8.CountOf_" #name}, \
  {&Counters::size_of_##name##_, "c:" "V8.SizeOf_" #name},
      INSTANCE_TYPE_LIST(SC)
240
#undef SC
241 242 243 244 245 246
#define SC(name)                            \
  {&Counters::count_of_CODE_TYPE_##name##_, \
    "c:" "V8.CountOf_CODE_TYPE-" #name},     \
  {&Counters::size_of_CODE_TYPE_##name##_,  \
    "c:" "V8.SizeOf_CODE_TYPE-" #name},
      CODE_KIND_LIST(SC)
247
#undef SC
248 249 250 251 252 253
#define SC(name)                              \
  {&Counters::count_of_FIXED_ARRAY_##name##_, \
    "c:" "V8.CountOf_FIXED_ARRAY-" #name},     \
  {&Counters::size_of_FIXED_ARRAY_##name##_,  \
    "c:" "V8.SizeOf_FIXED_ARRAY-" #name},
      FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(SC)
254
#undef SC
255 256 257
  };
  // clang-format on
  for (const auto& counter : kStatsCounters) {
258
    this->*counter.member = StatsCounter(this, counter.caption);
259
  }
260 261
}

262 263 264
void Counters::ResetCounterFunction(CounterLookupCallback f) {
  stats_table_.SetCounterFunction(f);

265 266 267
#define SC(name, caption) name##_.Reset();
  STATS_COUNTER_LIST_1(SC)
  STATS_COUNTER_LIST_2(SC)
268
  STATS_COUNTER_TS_LIST(SC)
269
  STATS_COUNTER_NATIVE_CODE_LIST(SC)
270 271
#undef SC

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
#define SC(name)              \
  count_of_##name##_.Reset(); \
  size_of_##name##_.Reset();
  INSTANCE_TYPE_LIST(SC)
#undef SC

#define SC(name)                        \
  count_of_CODE_TYPE_##name##_.Reset(); \
  size_of_CODE_TYPE_##name##_.Reset();
  CODE_KIND_LIST(SC)
#undef SC

#define SC(name)                          \
  count_of_FIXED_ARRAY_##name##_.Reset(); \
  size_of_FIXED_ARRAY_##name##_.Reset();
  FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(SC)
#undef SC
}

291 292
void Counters::ResetCreateHistogramFunction(CreateHistogramCallback f) {
  stats_table_.SetCreateHistogramFunction(f);
293

294 295 296 297
#define HR(name, caption, min, max, num_buckets) name##_.Reset();
  HISTOGRAM_RANGE_LIST(HR)
#undef HR

yangguo's avatar
yangguo committed
298
#define HT(name, caption, max, res) name##_.Reset();
299
  HISTOGRAM_TIMER_LIST(HT)
300 301
#undef HT

302
#define HT(name, caption, max, res) name##_.Reset();
303
  TIMED_HISTOGRAM_LIST(HT)
304 305
#undef HT

306
#define AHT(name, caption) name##_.Reset();
307
  AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
308 309
#undef AHT

310
#define HP(name, caption) name##_.Reset();
311
  HISTOGRAM_PERCENTAGE_LIST(HP)
312 313 314
#undef HP

#define HM(name, caption) name##_.Reset();
315
  HISTOGRAM_LEGACY_MEMORY_LIST(HM)
316 317 318
#undef HM
}

319 320 321
base::TimeTicks (*RuntimeCallTimer::Now)() =
    &base::TimeTicks::HighResolutionNow;

322 323 324
class RuntimeCallStatEntries {
 public:
  void Print(std::ostream& os) {
325 326
    if (total_call_count == 0) return;
    std::sort(entries.rbegin(), entries.rend());
327
    os << std::setw(50) << "Runtime Function/C++ Builtin" << std::setw(12)
328
       << "Time" << std::setw(18) << "Count" << std::endl
329
       << std::string(88, '=') << std::endl;
330 331 332
    for (Entry& entry : entries) {
      entry.SetTotal(total_time, total_call_count);
      entry.Print(os);
333
    }
334
    os << std::string(88, '-') << std::endl;
335
    Entry("Total", total_time, total_call_count).Print(os);
336 337
  }

338 339 340 341
  // By default, the compiler will usually inline this, which results in a large
  // binary size increase: std::vector::push_back expands to a large amount of
  // instructions, and this function is invoked repeatedly by macros.
  V8_NOINLINE void Add(RuntimeCallCounter* counter) {
342 343 344 345 346
    if (counter->count() == 0) return;
    entries.push_back(
        Entry(counter->name(), counter->time(), counter->count()));
    total_time += counter->time();
    total_call_count += counter->count();
347 348 349 350 351 352 353
  }

 private:
  class Entry {
   public:
    Entry(const char* name, base::TimeDelta time, uint64_t count)
        : name_(name),
354
          time_(time.InMicroseconds()),
355 356 357 358 359 360 361 362 363 364
          count_(count),
          time_percent_(100),
          count_percent_(100) {}

    bool operator<(const Entry& other) const {
      if (time_ < other.time_) return true;
      if (time_ > other.time_) return false;
      return count_ < other.count_;
    }

365
    V8_NOINLINE void Print(std::ostream& os) {
366
      os.precision(2);
367
      os << std::fixed << std::setprecision(2);
368
      os << std::setw(50) << name_;
369
      os << std::setw(10) << static_cast<double>(time_) / 1000 << "ms ";
370 371 372 373 374 375
      os << std::setw(6) << time_percent_ << "%";
      os << std::setw(10) << count_ << " ";
      os << std::setw(6) << count_percent_ << "%";
      os << std::endl;
    }

376 377
    V8_NOINLINE void SetTotal(base::TimeDelta total_time,
                              uint64_t total_count) {
378
      if (total_time.InMicroseconds() == 0) {
379 380
        time_percent_ = 0;
      } else {
381
        time_percent_ = 100.0 * time_ / total_time.InMicroseconds();
382
      }
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
      count_percent_ = 100.0 * count_ / total_count;
    }

   private:
    const char* name_;
    int64_t time_;
    uint64_t count_;
    double time_percent_;
    double count_percent_;
  };

  uint64_t total_call_count = 0;
  base::TimeDelta total_time;
  std::vector<Entry> entries;
};

399
void RuntimeCallCounter::Reset() {
400
  count_ = 0;
401
  time_ = 0;
402 403
}

404
void RuntimeCallCounter::Dump(v8::tracing::TracedValue* value) {
405
  value->BeginArray(name_);
406
  value->AppendDouble(count_);
407
  value->AppendDouble(time_);
408
  value->EndArray();
409 410
}

411
void RuntimeCallCounter::Add(RuntimeCallCounter* other) {
412
  count_ += other->count();
413
  time_ += other->time().InMicroseconds();
414 415 416 417 418 419 420 421 422 423 424 425 426
}

void RuntimeCallTimer::Snapshot() {
  base::TimeTicks now = Now();
  // Pause only / topmost timer in the timer stack.
  Pause(now);
  // Commit all the timer's elapsed time to the counters.
  RuntimeCallTimer* timer = this;
  while (timer != nullptr) {
    timer->CommitTimeToCounter();
    timer = timer->parent();
  }
  Resume(now);
427 428
}

429
RuntimeCallStats::RuntimeCallStats() : in_use_(false) {
430
  static const char* const kNames[] = {
431 432 433
#define CALL_BUILTIN_COUNTER(name) "GC_" #name,
      FOR_EACH_GC_COUNTER(CALL_BUILTIN_COUNTER)  //
#undef CALL_BUILTIN_COUNTER
434 435 436 437 438 439 440 441 442 443 444 445 446
#define CALL_RUNTIME_COUNTER(name) #name,
      FOR_EACH_MANUAL_COUNTER(CALL_RUNTIME_COUNTER)  //
#undef CALL_RUNTIME_COUNTER
#define CALL_RUNTIME_COUNTER(name, nargs, ressize) #name,
      FOR_EACH_INTRINSIC(CALL_RUNTIME_COUNTER)  //
#undef CALL_RUNTIME_COUNTER
#define CALL_BUILTIN_COUNTER(name) #name,
      BUILTIN_LIST_C(CALL_BUILTIN_COUNTER)  //
#undef CALL_BUILTIN_COUNTER
#define CALL_BUILTIN_COUNTER(name) "API_" #name,
      FOR_EACH_API_COUNTER(CALL_BUILTIN_COUNTER)  //
#undef CALL_BUILTIN_COUNTER
#define CALL_BUILTIN_COUNTER(name) #name,
447
      FOR_EACH_HANDLER_COUNTER(CALL_BUILTIN_COUNTER)  //
448 449
#undef CALL_BUILTIN_COUNTER
  };
450 451
  for (int i = 0; i < kNumberOfCounters; i++) {
    this->counters_[i] = RuntimeCallCounter(kNames[i]);
452 453 454
  }
}

455
void RuntimeCallStats::Enter(RuntimeCallTimer* timer,
456
                             RuntimeCallCounterId counter_id) {
457 458
  DCHECK(IsCalledOnTheSameThread());
  RuntimeCallCounter* counter = GetCounter(counter_id);
459
  DCHECK_NOT_NULL(counter->name());
460 461 462
  timer->Start(counter, current_timer());
  current_timer_.SetValue(timer);
  current_counter_.SetValue(counter);
463 464
}

465 466 467
void RuntimeCallStats::Leave(RuntimeCallTimer* timer) {
  DCHECK(IsCalledOnTheSameThread());
  RuntimeCallTimer* stack_top = current_timer();
468
  if (stack_top == nullptr) return;  // Missing timer is a result of Reset().
469
  CHECK(stack_top == timer);
470 471 472
  current_timer_.SetValue(timer->Stop());
  RuntimeCallTimer* cur_timer = current_timer();
  current_counter_.SetValue(cur_timer ? cur_timer->counter() : nullptr);
473 474
}

475
void RuntimeCallStats::Add(RuntimeCallStats* other) {
476 477
  for (int i = 0; i < kNumberOfCounters; i++) {
    GetCounter(i)->Add(other->GetCounter(i));
478 479 480
  }
}

481
// static
482
void RuntimeCallStats::CorrectCurrentCounterId(
483 484 485
    RuntimeCallCounterId counter_id) {
  DCHECK(IsCalledOnTheSameThread());
  RuntimeCallTimer* timer = current_timer();
486
  if (timer == nullptr) return;
487
  RuntimeCallCounter* counter = GetCounter(counter_id);
488
  timer->set_counter(counter);
489
  current_counter_.SetValue(counter);
490 491
}

492
bool RuntimeCallStats::IsCalledOnTheSameThread() {
Clemens Hammacher's avatar
Clemens Hammacher committed
493
  if (thread_id_.IsValid()) return thread_id_ == ThreadId::Current();
494 495 496 497
  thread_id_ = ThreadId::Current();
  return true;
}

498
void RuntimeCallStats::Print() {
499
  StdoutStream os;
500 501 502
  Print(os);
}

503 504
void RuntimeCallStats::Print(std::ostream& os) {
  RuntimeCallStatEntries entries;
505
  if (current_timer_.Value() != nullptr) {
506
    current_timer_.Value()->Snapshot();
507
  }
508 509
  for (int i = 0; i < kNumberOfCounters; i++) {
    entries.Add(GetCounter(i));
510
  }
511 512 513 514
  entries.Print(os);
}

void RuntimeCallStats::Reset() {
515
  if (V8_LIKELY(!TracingFlags::is_runtime_stats_enabled())) return;
516

517 518 519 520 521 522 523 524
  // In tracing, we only what to trace the time spent on top level trace events,
  // if runtime counter stack is not empty, we should clear the whole runtime
  // counter stack, and then reset counters so that we can dump counters into
  // top level trace events accurately.
  while (current_timer_.Value()) {
    current_timer_.SetValue(current_timer_.Value()->Stop());
  }

525 526
  for (int i = 0; i < kNumberOfCounters; i++) {
    GetCounter(i)->Reset();
527
  }
528 529

  in_use_ = true;
530 531
}

532
void RuntimeCallStats::Dump(v8::tracing::TracedValue* value) {
533 534
  for (int i = 0; i < kNumberOfCounters; i++) {
    if (GetCounter(i)->count() > 0) GetCounter(i)->Dump(value);
535
  }
536 537 538
  in_use_ = false;
}

539
WorkerThreadRuntimeCallStats::WorkerThreadRuntimeCallStats() {}
540 541

WorkerThreadRuntimeCallStats::~WorkerThreadRuntimeCallStats() {
542 543 544 545
  if (tls_key_) base::Thread::DeleteThreadLocalKey(*tls_key_);
}

base::Thread::LocalStorageKey WorkerThreadRuntimeCallStats::GetKey() {
546
  DCHECK(TracingFlags::is_runtime_stats_enabled());
547 548
  if (!tls_key_) tls_key_ = base::Thread::CreateThreadLocalKey();
  return *tls_key_;
549 550 551
}

RuntimeCallStats* WorkerThreadRuntimeCallStats::NewTable() {
552
  DCHECK(TracingFlags::is_runtime_stats_enabled());
553 554 555 556
  std::unique_ptr<RuntimeCallStats> new_table =
      base::make_unique<RuntimeCallStats>();
  RuntimeCallStats* result = new_table.get();

557
  base::MutexGuard lock(&mutex_);
558 559 560 561 562 563
  tables_.push_back(std::move(new_table));
  return result;
}

void WorkerThreadRuntimeCallStats::AddToMainTable(
    RuntimeCallStats* main_call_stats) {
564
  base::MutexGuard lock(&mutex_);
565 566 567 568 569 570 571 572 573 574
  for (auto& worker_stats : tables_) {
    DCHECK_NE(main_call_stats, worker_stats.get());
    main_call_stats->Add(worker_stats.get());
    worker_stats->Reset();
  }
}

WorkerThreadRuntimeCallStatsScope::WorkerThreadRuntimeCallStatsScope(
    WorkerThreadRuntimeCallStats* worker_stats)
    : table_(nullptr) {
575
  if (V8_LIKELY(!TracingFlags::is_runtime_stats_enabled())) return;
576 577 578 579 580 581 582 583

  table_ = reinterpret_cast<RuntimeCallStats*>(
      base::Thread::GetThreadLocal(worker_stats->GetKey()));
  if (table_ == nullptr) {
    table_ = worker_stats->NewTable();
    base::Thread::SetThreadLocal(worker_stats->GetKey(), table_);
  }

584 585
  if ((TracingFlags::runtime_stats.load(std::memory_order_relaxed) &
       v8::tracing::TracingCategoryObserver::ENABLED_BY_TRACING)) {
586 587 588 589 590 591 592
    table_->Reset();
  }
}

WorkerThreadRuntimeCallStatsScope::~WorkerThreadRuntimeCallStatsScope() {
  if (V8_LIKELY(table_ == nullptr)) return;

593
  if ((TracingFlags::runtime_stats.load(std::memory_order_relaxed) &
594 595 596 597 598 599 600 601 602
       v8::tracing::TracingCategoryObserver::ENABLED_BY_TRACING)) {
    auto value = v8::tracing::TracedValue::Create();
    table_->Dump(value.get());
    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("v8.runtime_stats"),
                         "V8.RuntimeStats", TRACE_EVENT_SCOPE_THREAD,
                         "runtime-call-stats", std::move(value));
  }
}

603 604
}  // namespace internal
}  // namespace v8