summaryrefslogtreecommitdiffstats
path: root/tools/profiler/core/ProfilerCPUFreq-linux-android.cpp
blob: c7efbbd75fb3606c5232f6baa9ad41886b1cc67d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ProfilerCPUFreq.h"
#include "nsThreadUtils.h"
#include <fcntl.h>
#include <unistd.h>

ProfilerCPUFreq::ProfilerCPUFreq() {
  if (!mCPUCounters.resize(mozilla::GetNumberOfProcessors())) {
    NS_WARNING("failing to resize the mCPUCounters vector");
    return;
  }

  for (unsigned cpuId = 0; cpuId < mCPUCounters.length(); ++cpuId) {
    const size_t buf_sz = 64;
    char buf[buf_sz];
    int rv = sprintf(
        buf, "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq", cpuId);
    if (NS_WARN_IF(rv < 0)) {
      continue;
    }

    int fd = open(buf, O_RDONLY);
    if (NS_WARN_IF(!fd)) {
      continue;
    }

    mCPUCounters[cpuId].fd = fd;
  }
}

ProfilerCPUFreq::~ProfilerCPUFreq() {
  for (CPUCounterInfo& CPUCounter : mCPUCounters) {
    int fd = CPUCounter.fd;
    if (NS_WARN_IF(!fd)) {
      continue;
    }
    close(fd);
    CPUCounter.fd = 0;
  }
}

uint32_t ProfilerCPUFreq::GetCPUSpeedMHz(unsigned cpuId) {
  MOZ_ASSERT(cpuId < mCPUCounters.length());
  int fd = mCPUCounters[cpuId].fd;
  if (NS_WARN_IF(!fd)) {
    return 0;
  }

  long rv = lseek(fd, 0, SEEK_SET);
  if (NS_WARN_IF(rv < 0)) {
    return 0;
  }

  const size_t buf_sz = 64;
  char buf[buf_sz];
  rv = read(fd, buf, buf_sz);
  if (NS_WARN_IF(rv < 0)) {
    return 0;
  }

  int cpufreq = 0;
  rv = sscanf(buf, "%u", &cpufreq);
  if (NS_WARN_IF(rv != 1)) {
    return 0;
  }

  // Convert kHz to MHz, rounding to the nearst 10Mhz, to ignore tiny
  // variations that are likely due to rounding errors.
  return uint32_t(cpufreq / 10000) * 10;
}