Skip to content

Commit 46d3c84

Browse files
authored
Convert uses of const char* to std::string (#1567)
* Convert uses of const char* to std::string * fix sanitizer builds * reformat user guide * include python bindings * clang-format
1 parent 68aa190 commit 46d3c84

File tree

11 files changed

+56
-56
lines changed

11 files changed

+56
-56
lines changed

bindings/python/google_benchmark/benchmark.cc

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ std::vector<std::string> Initialize(const std::vector<std::string>& argv) {
3434
return remaining_argv;
3535
}
3636

37-
benchmark::internal::Benchmark* RegisterBenchmark(const char* name,
37+
benchmark::internal::Benchmark* RegisterBenchmark(const std::string& name,
3838
nb::callable f) {
3939
return benchmark::RegisterBenchmark(
4040
name, [f](benchmark::State& state) { f(&state); });
@@ -165,8 +165,8 @@ NB_MODULE(_benchmark, m) {
165165
.def_prop_rw("complexity_n", &State::complexity_length_n,
166166
&State::SetComplexityN)
167167
.def_prop_rw("items_processed", &State::items_processed,
168-
&State::SetItemsProcessed)
169-
.def("set_label", (void (State::*)(const char*)) & State::SetLabel)
168+
&State::SetItemsProcessed)
169+
.def("set_label", &State::SetLabel)
170170
.def("range", &State::range, nb::arg("pos") = 0)
171171
.def_prop_ro("iterations", &State::iterations)
172172
.def_prop_ro("name", &State::name)

docs/user_guide.md

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
[Exiting with an Error](#exiting-with-an-error)
5858

59-
[A Faster KeepRunning Loop](#a-faster-keep-running-loop)
59+
[A Faster `KeepRunning` Loop](#a-faster-keep-running-loop)
6060

6161
## Benchmarking Tips
6262

@@ -271,10 +271,12 @@ information about the machine on which the benchmarks are run.
271271
Global setup/teardown specific to each benchmark can be done by
272272
passing a callback to Setup/Teardown:
273273
274-
The setup/teardown callbacks will be invoked once for each benchmark.
275-
If the benchmark is multi-threaded (will run in k threads), they will be invoked exactly once before
276-
each run with k threads.
277-
If the benchmark uses different size groups of threads, the above will be true for each size group.
274+
The setup/teardown callbacks will be invoked once for each benchmark. If the
275+
benchmark is multi-threaded (will run in k threads), they will be invoked
276+
exactly once before each run with k threads.
277+
278+
If the benchmark uses different size groups of threads, the above will be true
279+
for each size group.
278280
279281
Eg.,
280282
@@ -1142,7 +1144,7 @@ int main(int argc, char** argv) {
11421144

11431145
When errors caused by external influences, such as file I/O and network
11441146
communication, occur within a benchmark the
1145-
`State::SkipWithError(const char* msg)` function can be used to skip that run
1147+
`State::SkipWithError(const std::string& msg)` function can be used to skip that run
11461148
of benchmark and report the error. Note that only future iterations of the
11471149
`KeepRunning()` are skipped. For the ranged-for version of the benchmark loop
11481150
Users must explicitly exit the loop, otherwise all iterations will be performed.
@@ -1253,7 +1255,8 @@ the benchmark loop should be preferred.
12531255
If you see this error:
12541256

12551257
```
1256-
***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
1258+
***WARNING*** CPU scaling is enabled, the benchmark real time measurements may
1259+
be noisy and will incur extra overhead.
12571260
```
12581261

12591262
you might want to disable the CPU frequency scaling while running the

include/benchmark/benchmark.h

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -865,11 +865,7 @@ class BENCHMARK_EXPORT State {
865865
// BM_Compress 50 50 14115038 compress:27.3%
866866
//
867867
// REQUIRES: a benchmark has exited its benchmarking loop.
868-
void SetLabel(const char* label);
869-
870-
void BENCHMARK_ALWAYS_INLINE SetLabel(const std::string& str) {
871-
this->SetLabel(str.c_str());
872-
}
868+
void SetLabel(const std::string& label);
873869

874870
// Range arguments for this run. CHECKs if the argument has been set.
875871
BENCHMARK_ALWAYS_INLINE
@@ -1249,8 +1245,8 @@ class BENCHMARK_EXPORT Benchmark {
12491245
TimeUnit GetTimeUnit() const;
12501246

12511247
protected:
1252-
explicit Benchmark(const char* name);
1253-
void SetName(const char* name);
1248+
explicit Benchmark(const std::string& name);
1249+
void SetName(const std::string& name);
12541250

12551251
public:
12561252
const char* GetName() const;
@@ -1305,12 +1301,12 @@ class BENCHMARK_EXPORT Benchmark {
13051301
// the specified functor 'fn'.
13061302
//
13071303
// RETURNS: A pointer to the registered benchmark.
1308-
internal::Benchmark* RegisterBenchmark(const char* name,
1304+
internal::Benchmark* RegisterBenchmark(const std::string& name,
13091305
internal::Function* fn);
13101306

13111307
#if defined(BENCHMARK_HAS_CXX11)
13121308
template <class Lambda>
1313-
internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn);
1309+
internal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn);
13141310
#endif
13151311

13161312
// Remove all registered benchmarks. All pointers to previously registered
@@ -1322,7 +1318,7 @@ namespace internal {
13221318
// (ie those created using the BENCHMARK(...) macros.
13231319
class BENCHMARK_EXPORT FunctionBenchmark : public Benchmark {
13241320
public:
1325-
FunctionBenchmark(const char* name, Function* func)
1321+
FunctionBenchmark(const std::string& name, Function* func)
13261322
: Benchmark(name), func_(func) {}
13271323

13281324
void Run(State& st) BENCHMARK_OVERRIDE;
@@ -1339,28 +1335,28 @@ class LambdaBenchmark : public Benchmark {
13391335

13401336
private:
13411337
template <class OLambda>
1342-
LambdaBenchmark(const char* name, OLambda&& lam)
1338+
LambdaBenchmark(const std::string& name, OLambda&& lam)
13431339
: Benchmark(name), lambda_(std::forward<OLambda>(lam)) {}
13441340

13451341
LambdaBenchmark(LambdaBenchmark const&) = delete;
13461342

13471343
template <class Lam> // NOLINTNEXTLINE(readability-redundant-declaration)
1348-
friend Benchmark* ::benchmark::RegisterBenchmark(const char*, Lam&&);
1344+
friend Benchmark* ::benchmark::RegisterBenchmark(const std::string&, Lam&&);
13491345

13501346
Lambda lambda_;
13511347
};
13521348
#endif
13531349
} // namespace internal
13541350

1355-
inline internal::Benchmark* RegisterBenchmark(const char* name,
1351+
inline internal::Benchmark* RegisterBenchmark(const std::string& name,
13561352
internal::Function* fn) {
13571353
return internal::RegisterBenchmarkInternal(
13581354
::new internal::FunctionBenchmark(name, fn));
13591355
}
13601356

13611357
#ifdef BENCHMARK_HAS_CXX11
13621358
template <class Lambda>
1363-
internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn) {
1359+
internal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn) {
13641360
using BenchType =
13651361
internal::LambdaBenchmark<typename std::decay<Lambda>::type>;
13661362
return internal::RegisterBenchmarkInternal(
@@ -1371,7 +1367,7 @@ internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn) {
13711367
#if defined(BENCHMARK_HAS_CXX11) && \
13721368
(!defined(BENCHMARK_GCC_VERSION) || BENCHMARK_GCC_VERSION >= 409)
13731369
template <class Lambda, class... Args>
1374-
internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn,
1370+
internal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn,
13751371
Args&&... args) {
13761372
return benchmark::RegisterBenchmark(
13771373
name, [=](benchmark::State& st) { fn(st, args...); });

src/benchmark.cc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ void State::SetIterationTime(double seconds) {
273273
timer_->SetIterationTime(seconds);
274274
}
275275

276-
void State::SetLabel(const char* label) {
276+
void State::SetLabel(const std::string& label) {
277277
MutexLock l(manager_->GetBenchmarkMutex());
278278
manager_->results.report_label_ = label;
279279
}

src/benchmark_register.cc

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ bool FindBenchmarksInternal(const std::string& re,
204204
// Benchmark
205205
//=============================================================================//
206206

207-
Benchmark::Benchmark(const char* name)
207+
Benchmark::Benchmark(const std::string& name)
208208
: name_(name),
209209
aggregation_report_mode_(ARM_Unspecified),
210210
time_unit_(GetDefaultTimeUnit()),
@@ -230,7 +230,7 @@ Benchmark::Benchmark(const char* name)
230230
Benchmark::~Benchmark() {}
231231

232232
Benchmark* Benchmark::Name(const std::string& name) {
233-
SetName(name.c_str());
233+
SetName(name);
234234
return this;
235235
}
236236

@@ -468,7 +468,7 @@ Benchmark* Benchmark::ThreadPerCpu() {
468468
return this;
469469
}
470470

471-
void Benchmark::SetName(const char* name) { name_ = name; }
471+
void Benchmark::SetName(const std::string& name) { name_ = name; }
472472

473473
const char* Benchmark::GetName() const { return name_.c_str(); }
474474

src/benchmark_runner.cc

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -177,11 +177,10 @@ BenchTimeType ParseBenchMinTime(const std::string& value) {
177177
}
178178

179179
if (value.back() == 'x') {
180-
const char* iters_str = value.c_str();
181180
char* p_end;
182181
// Reset errno before it's changed by strtol.
183182
errno = 0;
184-
IterationCount num_iters = std::strtol(iters_str, &p_end, 10);
183+
IterationCount num_iters = std::strtol(value.c_str(), &p_end, 10);
185184

186185
// After a valid parse, p_end should have been set to
187186
// point to the 'x' suffix.
@@ -194,7 +193,6 @@ BenchTimeType ParseBenchMinTime(const std::string& value) {
194193
return ret;
195194
}
196195

197-
const char* time_str = value.c_str();
198196
bool has_suffix = value.back() == 's';
199197
if (!has_suffix) {
200198
BM_VLOG(0) << "Value passed to --benchmark_min_time should have a suffix. "
@@ -204,7 +202,7 @@ BenchTimeType ParseBenchMinTime(const std::string& value) {
204202
char* p_end;
205203
// Reset errno before it's changed by strtod.
206204
errno = 0;
207-
double min_time = std::strtod(time_str, &p_end);
205+
double min_time = std::strtod(value.c_str(), &p_end);
208206

209207
// After a successful parse, p_end should point to the suffix 's',
210208
// or the end of the string if the suffix was omitted.

src/json_reporter.cc

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,8 @@ void JSONReporter::PrintRunData(Run const& run) {
297297
out << ",\n"
298298
<< indent << FormatKV("max_bytes_used", memory_result.max_bytes_used);
299299

300-
auto report_if_present = [&out, &indent](const char* label, int64_t val) {
300+
auto report_if_present = [&out, &indent](const std::string& label,
301+
int64_t val) {
301302
if (val != MemoryManager::TombstoneValue)
302303
out << ",\n" << indent << FormatKV(label, val);
303304
};

test/output_test.h

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ std::string GetFileReporterOutput(int argc, char* argv[]);
8585
struct Results;
8686
typedef std::function<void(Results const&)> ResultsCheckFn;
8787

88-
size_t AddChecker(const char* bm_name_pattern, const ResultsCheckFn& fn);
88+
size_t AddChecker(const std::string& bm_name_pattern, const ResultsCheckFn& fn);
8989

9090
// Class holding the results of a benchmark.
9191
// It is passed in calls to checker functions.
@@ -117,7 +117,7 @@ struct Results {
117117

118118
// get the string for a result by name, or nullptr if the name
119119
// is not found
120-
const std::string* Get(const char* entry_name) const {
120+
const std::string* Get(const std::string& entry_name) const {
121121
auto it = values.find(entry_name);
122122
if (it == values.end()) return nullptr;
123123
return &it->second;
@@ -126,20 +126,20 @@ struct Results {
126126
// get a result by name, parsed as a specific type.
127127
// NOTE: for counters, use GetCounterAs instead.
128128
template <class T>
129-
T GetAs(const char* entry_name) const;
129+
T GetAs(const std::string& entry_name) const;
130130

131131
// counters are written as doubles, so they have to be read first
132132
// as a double, and only then converted to the asked type.
133133
template <class T>
134-
T GetCounterAs(const char* entry_name) const {
134+
T GetCounterAs(const std::string& entry_name) const {
135135
double dval = GetAs<double>(entry_name);
136136
T tval = static_cast<T>(dval);
137137
return tval;
138138
}
139139
};
140140

141141
template <class T>
142-
T Results::GetAs(const char* entry_name) const {
142+
T Results::GetAs(const std::string& entry_name) const {
143143
auto* sv = Get(entry_name);
144144
BM_CHECK(sv != nullptr && !sv->empty());
145145
std::stringstream ss;

test/output_test_helper.cc

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ std::vector<std::string> ResultsChecker::SplitCsv_(const std::string& line) {
299299

300300
} // end namespace internal
301301

302-
size_t AddChecker(const char* bm_name, const ResultsCheckFn& fn) {
302+
size_t AddChecker(const std::string& bm_name, const ResultsCheckFn& fn) {
303303
auto& rc = internal::GetResultsChecker();
304304
rc.Add(bm_name, fn);
305305
return rc.results.size();
@@ -394,27 +394,27 @@ void RunOutputTests(int argc, char* argv[]) {
394394
benchmark::JSONReporter JR;
395395
benchmark::CSVReporter CSVR;
396396
struct ReporterTest {
397-
const char* name;
397+
std::string name;
398398
std::vector<TestCase>& output_cases;
399399
std::vector<TestCase>& error_cases;
400400
benchmark::BenchmarkReporter& reporter;
401401
std::stringstream out_stream;
402402
std::stringstream err_stream;
403403

404-
ReporterTest(const char* n, std::vector<TestCase>& out_tc,
404+
ReporterTest(const std::string& n, std::vector<TestCase>& out_tc,
405405
std::vector<TestCase>& err_tc,
406406
benchmark::BenchmarkReporter& br)
407407
: name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) {
408408
reporter.SetOutputStream(&out_stream);
409409
reporter.SetErrorStream(&err_stream);
410410
}
411411
} TestCases[] = {
412-
{"ConsoleReporter", GetTestCaseList(TC_ConsoleOut),
412+
{std::string("ConsoleReporter"), GetTestCaseList(TC_ConsoleOut),
413413
GetTestCaseList(TC_ConsoleErr), CR},
414-
{"JSONReporter", GetTestCaseList(TC_JSONOut), GetTestCaseList(TC_JSONErr),
415-
JR},
416-
{"CSVReporter", GetTestCaseList(TC_CSVOut), GetTestCaseList(TC_CSVErr),
417-
CSVR},
414+
{std::string("JSONReporter"), GetTestCaseList(TC_JSONOut),
415+
GetTestCaseList(TC_JSONErr), JR},
416+
{std::string("CSVReporter"), GetTestCaseList(TC_CSVOut),
417+
GetTestCaseList(TC_CSVErr), CSVR},
418418
};
419419

420420
// Create the test reporter and run the benchmarks.
@@ -423,7 +423,8 @@ void RunOutputTests(int argc, char* argv[]) {
423423
benchmark::RunSpecifiedBenchmarks(&test_rep);
424424

425425
for (auto& rep_test : TestCases) {
426-
std::string msg = std::string("\nTesting ") + rep_test.name + " Output\n";
426+
std::string msg =
427+
std::string("\nTesting ") + rep_test.name + std::string(" Output\n");
427428
std::string banner(msg.size() - 1, '-');
428429
std::cout << banner << msg << banner << "\n";
429430

@@ -440,7 +441,7 @@ void RunOutputTests(int argc, char* argv[]) {
440441
// the checks to subscribees.
441442
auto& csv = TestCases[2];
442443
// would use == but gcc spits a warning
443-
BM_CHECK(std::strcmp(csv.name, "CSVReporter") == 0);
444+
BM_CHECK(csv.name == std::string("CSVReporter"));
444445
internal::GetResultsChecker().CheckResults(csv.out_stream);
445446
}
446447

test/register_benchmark_test.cc

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@ class TestReporter : public benchmark::ConsoleReporter {
1919
};
2020

2121
struct TestCase {
22-
std::string name;
23-
const char* label;
22+
const std::string name;
23+
const std::string label;
2424
// Note: not explicit as we rely on it being converted through ADD_CASES.
25-
TestCase(const char* xname) : TestCase(xname, nullptr) {}
26-
TestCase(const char* xname, const char* xlabel)
25+
TestCase(const std::string& xname) : TestCase(xname, "") {}
26+
TestCase(const std::string& xname, const std::string& xlabel)
2727
: name(xname), label(xlabel) {}
2828

2929
typedef benchmark::BenchmarkReporter::Run Run;
@@ -32,7 +32,7 @@ struct TestCase {
3232
// clang-format off
3333
BM_CHECK(name == run.benchmark_name()) << "expected " << name << " got "
3434
<< run.benchmark_name();
35-
if (label) {
35+
if (!label.empty()) {
3636
BM_CHECK(run.report_label == label) << "expected " << label << " got "
3737
<< run.report_label;
3838
} else {
@@ -123,7 +123,7 @@ void TestRegistrationAtRuntime() {
123123
{
124124
CustomFixture fx;
125125
benchmark::RegisterBenchmark("custom_fixture", fx);
126-
AddCases({"custom_fixture"});
126+
AddCases({std::string("custom_fixture")});
127127
}
128128
#endif
129129
#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK

test/skip_with_error_test.cc

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ struct TestCase {
4848

4949
std::vector<TestCase> ExpectedResults;
5050

51-
int AddCases(const char* base_name, std::initializer_list<TestCase> const& v) {
51+
int AddCases(const std::string& base_name,
52+
std::initializer_list<TestCase> const& v) {
5253
for (auto TC : v) {
5354
TC.name = base_name + TC.name;
5455
ExpectedResults.push_back(std::move(TC));

0 commit comments

Comments
 (0)