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.
4
5 #include "base/memory/memory_pressure_monitor.h"
6
7 #include "base/logging.h"
8 #include "base/metrics/histogram_macros.h"
9
10 namespace base {
11 namespace {
12
13 MemoryPressureMonitor* g_monitor = nullptr;
14
15 // Enumeration of UMA memory pressure levels. This needs to be kept in sync with
16 // histograms.xml and the memory pressure levels defined in
17 // MemoryPressureListener.
18 enum MemoryPressureLevelUMA {
19 UMA_MEMORY_PRESSURE_LEVEL_NONE = 0,
20 UMA_MEMORY_PRESSURE_LEVEL_MODERATE = 1,
21 UMA_MEMORY_PRESSURE_LEVEL_CRITICAL = 2,
22 // This must be the last value in the enum.
23 UMA_MEMORY_PRESSURE_LEVEL_COUNT,
24 };
25
26 // Converts a memory pressure level to an UMA enumeration value.
MemoryPressureLevelToUmaEnumValue(base::MemoryPressureListener::MemoryPressureLevel level)27 MemoryPressureLevelUMA MemoryPressureLevelToUmaEnumValue(
28 base::MemoryPressureListener::MemoryPressureLevel level) {
29 switch (level) {
30 case MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE:
31 return UMA_MEMORY_PRESSURE_LEVEL_NONE;
32 case MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE:
33 return UMA_MEMORY_PRESSURE_LEVEL_MODERATE;
34 case MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL:
35 return UMA_MEMORY_PRESSURE_LEVEL_CRITICAL;
36 }
37 NOTREACHED();
38 return UMA_MEMORY_PRESSURE_LEVEL_NONE;
39 }
40
41 } // namespace
42
MemoryPressureMonitor()43 MemoryPressureMonitor::MemoryPressureMonitor() {
44 DCHECK(!g_monitor);
45 g_monitor = this;
46 }
47
~MemoryPressureMonitor()48 MemoryPressureMonitor::~MemoryPressureMonitor() {
49 DCHECK(g_monitor);
50 g_monitor = nullptr;
51 }
52
53 // static
Get()54 MemoryPressureMonitor* MemoryPressureMonitor::Get() {
55 return g_monitor;
56 }
RecordMemoryPressure(base::MemoryPressureListener::MemoryPressureLevel level,int ticks)57 void MemoryPressureMonitor::RecordMemoryPressure(
58 base::MemoryPressureListener::MemoryPressureLevel level,
59 int ticks) {
60 // Use the more primitive STATIC_HISTOGRAM_POINTER_BLOCK macro because the
61 // simple UMA_HISTOGRAM macros don't expose 'AddCount' functionality.
62 STATIC_HISTOGRAM_POINTER_BLOCK(
63 "Memory.PressureLevel",
64 AddCount(MemoryPressureLevelToUmaEnumValue(level), ticks),
65 base::LinearHistogram::FactoryGet(
66 "Memory.PressureLevel", 1, UMA_MEMORY_PRESSURE_LEVEL_COUNT,
67 UMA_MEMORY_PRESSURE_LEVEL_COUNT + 1,
68 base::HistogramBase::kUmaTargetedHistogramFlag));
69 }
70
71 } // namespace base
72