Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
cpu_affinity.cc
Go to the documentation of this file.
1// Copyright 2013 The Flutter 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 "flutter/fml/platform/android/cpu_affinity.h"
6
7#include <pthread.h>
8#include <sys/resource.h>
9#include <sys/time.h>
10#include <unistd.h>
11#include <mutex>
12#include <optional>
13#include <thread>
14#include "flutter/fml/logging.h"
15
16namespace fml {
17
18/// The CPUSpeedTracker is initialized once the first time a thread affinity is
19/// requested.
20std::once_flag gCPUTrackerFlag;
22
23// For each CPU index provided, attempts to open the file
24// /sys/devices/system/cpu/cpu$NUM/cpufreq/cpuinfo_max_freq and parse a number
25// containing the CPU frequency.
26void InitCPUInfo(size_t cpu_count) {
27 std::vector<CpuIndexAndSpeed> cpu_speeds;
28
29 for (auto i = 0u; i < cpu_count; i++) {
30 auto path = "/sys/devices/system/cpu/cpu" + std::to_string(i) +
31 "/cpufreq/cpuinfo_max_freq";
32 auto speed = ReadIntFromFile(path);
33 if (speed.has_value()) {
34 cpu_speeds.push_back({.index = i, .speed = speed.value()});
35 }
36 }
37 gCPUTracker = new CPUSpeedTracker(cpu_speeds);
38}
39
41 // Populate CPU Info if uninitialized.
42 auto count = std::thread::hardware_concurrency();
43 std::call_once(gCPUTrackerFlag, [count]() { InitCPUInfo(count); });
44 if (gCPUTracker == nullptr || !gCPUTracker->IsValid()) {
45 return false;
46 }
47 return true;
48}
49
50std::optional<size_t> AndroidEfficiencyCoreCount() {
51 if (!SetUpCPUTracker()) {
52 return true;
53 }
55 FML_DCHECK(result > 0);
56 return result;
57}
58
60 if (!SetUpCPUTracker()) {
61 return true;
62 }
63
64 cpu_set_t set;
65 CPU_ZERO(&set);
66 for (const auto index : gCPUTracker->GetIndices(affinity)) {
67 CPU_SET(index, &set);
68 }
69 return sched_setaffinity(gettid(), sizeof(set), &set) == 0;
70}
71
72} // namespace fml
int count
A class that computes the correct CPU indices for a requested CPU affinity.
const std::vector< size_t > & GetIndices(CpuAffinity affinity) const
Return the set of CPU indices for the requested CPU affinity.
bool IsValid() const
The class is valid if it has more than one CPU index and a distinct set of efficiency or performance ...
GAsyncResult * result
#define FML_DCHECK(condition)
Definition logging.h:103
CpuAffinity
@ kEfficiency
Request CPU affinity for the efficiency cores.
std::optional< int64_t > ReadIntFromFile(const std::string &path)
static CPUSpeedTracker * gCPUTracker
std::optional< size_t > AndroidEfficiencyCoreCount()
Android specific implementation of EfficiencyCoreCount.
bool AndroidRequestAffinity(CpuAffinity affinity)
Android specific implementation of RequestAffinity.
std::once_flag gCPUTrackerFlag
bool SetUpCPUTracker()
void InitCPUInfo(size_t cpu_count)