Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf_counters: Initialize once only when needed #1656

Merged
merged 3 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/perf_counters.cc
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,20 @@ size_t PerfCounterValues::Read(const std::vector<int>& leaders) {

const bool PerfCounters::kSupported = true;

bool PerfCounters::Initialize() { return pfm_initialize() == PFM_SUCCESS; }
// Initializes libpfm only on the first call. Returns whether that single
// initialization was successful
static bool InitLibPfmOnce() {
jmr marked this conversation as resolved.
Show resolved Hide resolved
// Function-scope static gets initialized only once on first call.
static const bool success = []() {
return pfm_initialize() == PFM_SUCCESS;
}();
return success;
}

bool PerfCounters::Initialize() { return InitLibPfmOnce(); }

bool PerfCounters::IsCounterSupported(const std::string& name) {
InitLibPfmOnce();
perf_event_attr_t attr;
std::memset(&attr, 0, sizeof(attr));
pfm_perf_encode_arg_t arg;
Expand All @@ -73,6 +84,10 @@ bool PerfCounters::IsCounterSupported(const std::string& name) {

PerfCounters PerfCounters::Create(
const std::vector<std::string>& counter_names) {
if (!counter_names.empty()) {
InitLibPfmOnce();
}

// Valid counters will populate these arrays but we start empty
std::vector<std::string> valid_names;
std::vector<int> counter_ids;
Expand Down
2 changes: 0 additions & 2 deletions src/perf_counters.h
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,6 @@ class BENCHMARK_EXPORT PerfCountersMeasurement final {
PerfCounterValues end_values_;
};

BENCHMARK_UNUSED static bool perf_init_anchor = PerfCounters::Initialize();

} // namespace internal
} // namespace benchmark

Expand Down
Loading