Add SetBenchmarkFilter() to set --benchmark_filter flag value in user code (#1362) * Add SetBenchmarkFilter() to set --benchmark_filter flag value in user code. Use case: Provide an API to set this flag indepedence of the flag's implementation (ie., absl flag vs benchmark's flag facility) * add test * added notes on Initialize()
diff --git a/include/benchmark/benchmark.h b/include/benchmark/benchmark.h index 7e146db..da5b890 100644 --- a/include/benchmark/benchmark.h +++ b/include/benchmark/benchmark.h
@@ -302,6 +302,12 @@ // Returns the current value of --benchmark_filter. BENCHMARK_EXPORT std::string GetBenchmarkFilter(); +// Sets a new value to --benchmark_filter. (This will override this flag's +// current value). +// Should be called after `benchmark::Initialize()`, as +// `benchmark::Initialize()` will override the flag's value. +BENCHMARK_EXPORT void SetBenchmarkFilter(std::string value); + // Creates a default display reporter. Used by the library when no display // reporter is provided, but also made available for external use in case a // custom reporter should respect the `--benchmark_format` flag as a fallback
diff --git a/src/benchmark.cc b/src/benchmark.cc index 57958b1..eb7f656 100644 --- a/src/benchmark.cc +++ b/src/benchmark.cc
@@ -535,6 +535,10 @@ std::string GetBenchmarkFilter() { return FLAGS_benchmark_filter; } +void SetBenchmarkFilter(std::string value) { + FLAGS_benchmark_filter = std::move(value); +} + void RegisterMemoryManager(MemoryManager* manager) { internal::memory_manager = manager; }
diff --git a/test/spec_arg_test.cc b/test/spec_arg_test.cc index 043db1b..68ab135 100644 --- a/test/spec_arg_test.cc +++ b/test/spec_arg_test.cc
@@ -91,5 +91,15 @@ << matched_functions.front() << "]\n"; return 2; } + + // Test that SetBenchmarkFilter works. + const std::string golden_value = "golden_value"; + benchmark::SetBenchmarkFilter(golden_value); + std::string current_value = benchmark::GetBenchmarkFilter(); + if (golden_value != current_value) { + std::cerr << "Expected [" << golden_value + << "] for --benchmark_filter but got [" << current_value << "]\n"; + return 3; + } return 0; }