1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #include "ProfilerCPUFreq.h"
6 #include "nsThreadUtils.h"
10 ProfilerCPUFreq::ProfilerCPUFreq() {
11 if (!mCPUCounters
.resize(mozilla::GetNumberOfProcessors())) {
12 NS_WARNING("failing to resize the mCPUCounters vector");
16 for (unsigned cpuId
= 0; cpuId
< mCPUCounters
.length(); ++cpuId
) {
17 const size_t buf_sz
= 64;
20 buf
, "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq", cpuId
);
21 if (NS_WARN_IF(rv
< 0)) {
25 int fd
= open(buf
, O_RDONLY
);
26 if (NS_WARN_IF(!fd
)) {
30 mCPUCounters
[cpuId
].fd
= fd
;
34 ProfilerCPUFreq::~ProfilerCPUFreq() {
35 for (CPUCounterInfo
& CPUCounter
: mCPUCounters
) {
36 int fd
= CPUCounter
.fd
;
37 if (NS_WARN_IF(!fd
)) {
45 uint32_t ProfilerCPUFreq::GetCPUSpeedMHz(unsigned cpuId
) {
46 MOZ_ASSERT(cpuId
< mCPUCounters
.length());
47 int fd
= mCPUCounters
[cpuId
].fd
;
48 if (NS_WARN_IF(!fd
)) {
52 long rv
= lseek(fd
, 0, SEEK_SET
);
53 if (NS_WARN_IF(rv
< 0)) {
57 const size_t buf_sz
= 64;
59 rv
= read(fd
, buf
, buf_sz
);
60 if (NS_WARN_IF(rv
< 0)) {
65 rv
= sscanf(buf
, "%u", &cpufreq
);
66 if (NS_WARN_IF(rv
!= 1)) {
70 // Convert kHz to MHz, rounding to the nearst 10Mhz, to ignore tiny
71 // variations that are likely due to rounding errors.
72 return uint32_t(cpufreq
/ 10000) * 10;