diff --git a/.gitignore b/.gitignore index 5dfc6384..8e2bb06b 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ Makefile bin/ cmake_install.cmake lib/ +tags diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index a713aa9b..89cc5076 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,11 @@ benchmark ========= +[![Build Status](https://drone.io/github.com/google/benchmark/status.png)](https://drone.io/github.com/google/benchmark/latest) + A library to support the benchmarking of functions, similar to unit-tests. +Discussion group: https://groups.google.com/d/forum/benchmark-discuss + Example usage: Define a function that executes the code to be measured a specified number of times: diff --git a/include/benchmark/benchmark.h b/include/benchmark/benchmark.h index 4cf1b520..45ab35b8 100644 --- a/include/benchmark/benchmark.h +++ b/include/benchmark/benchmark.h @@ -145,24 +145,27 @@ BENCHMARK(BM_MultiThreaded)->Threads(4); #include "macros.h" namespace benchmark { -// If the --benchmarks flag is empty, do nothing. -// -// Otherwise, run all benchmarks specified by the --benchmarks flag, +class BenchmarkReporter; + +void Initialize(int* argc, const char** argv); + +// Otherwise, run all benchmarks specified by the --benchmark_filter flag, // and exit after running the benchmarks. -extern void RunSpecifiedBenchmarks(); +void RunSpecifiedBenchmarks(const BenchmarkReporter* reporter = nullptr); // ------------------------------------------------------ // Routines that can be called from within a benchmark // // REQUIRES: a benchmark is currently executing -extern void SetLabel(const std::string& label); +void SetLabel(const std::string& label); // If this routine is called, peak memory allocation past this point in the // benchmark is reported at the end of the benchmark report line. (It is // computed by running the benchmark once with a single iteration and a memory // tracer.) -extern void MemoryUsage(); +// TODO(dominic) +//void MemoryUsage(); // If a particular benchmark is I/O bound, or if for some reason CPU // timings are not representative, call this method from within the @@ -170,7 +173,7 @@ extern void MemoryUsage(); // control how many iterations are run, and in the printing of // items/second or MB/seconds values. If not called, the cpu time // used by the benchmark will be used. -extern void UseRealTime(); +void UseRealTime(); namespace internal { class Benchmark; @@ -290,15 +293,73 @@ class State { DISALLOW_COPY_AND_ASSIGN(State); }; +// Interface for custom benchmark result printers. +// By default, benchmark reports are printed to stdout. However an application +// can control the destination of the reports by calling +// RunSpecifiedBenchmarks and passing it a custom reporter object. +// The reporter object must implement the following interface. +class BenchmarkReporter { + public: + struct Context { + int num_cpus; + double mhz_per_cpu; + //std::string cpu_info; + bool cpu_scaling_enabled; + + // The number of chars in the longest benchmark name. + int name_field_width; + }; + + struct Run { + Run() : + thread_index(-1), + iterations(1), + real_accumulated_time(0), + cpu_accumulated_time(0), + bytes_per_second(0), + items_per_second(0), + max_heapbytes_used(0) {} + + std::string benchmark_name; + std::string report_label; + int thread_index; + int64_t iterations; + double real_accumulated_time; + double cpu_accumulated_time; + + // Zero if not set by benchmark. + double bytes_per_second; + double items_per_second; + + // This is set to 0.0 if memory tracing is not enabled. + double max_heapbytes_used; + }; + + // Called once for every suite of benchmarks run. + // The parameter "context" contains information that the + // reporter may wish to use when generating its report, for example the + // platform under which the benchmarks are running. The benchmark run is + // never started if this function returns false, allowing the reporter + // to skip runs based on the context information. + virtual bool ReportContext(const Context& context) const = 0; + + // Called once for each group of benchmark runs, gives information about + // cpu-time and heap memory usage during the benchmark run. + // Note that all the grouped benchmark runs should refer to the same + // benchmark, thus have the same name. + virtual void ReportRuns(const std::vector& report) const = 0; + + virtual ~BenchmarkReporter() {} +}; + namespace internal { -class BenchmarkReporter; typedef std::function BenchmarkFunction; // Run all benchmarks whose name is a partial match for the regular // expression in "spec". The results of benchmark runs are fed to "reporter". void RunMatchingBenchmarks(const std::string& spec, - BenchmarkReporter* reporter); + const BenchmarkReporter* reporter); // Extract the list of benchmark names that match the specified regular // expression. @@ -376,8 +437,6 @@ class Benchmark { // Equivalent to ThreadRange(NumCPUs(), NumCPUs()) Benchmark* ThreadPerCpu(); - // TODO(dominic): Control whether or not real-time is used for this benchmark - // ------------------------------- // Following methods are not useful for clients @@ -411,100 +470,31 @@ class Benchmark { static void AddRange(std::vector* dst, int lo, int hi, int mult); static double MeasurePeakHeapMemory(const Instance& b); - static void RunInstance(const Instance& b, BenchmarkReporter* br); + static void RunInstance(const Instance& b, const BenchmarkReporter* br); friend class ::benchmark::State; friend struct ::benchmark::internal::Benchmark::Instance; - friend void ::benchmark::internal::RunMatchingBenchmarks(const std::string&, - BenchmarkReporter*); + friend void ::benchmark::internal::RunMatchingBenchmarks( + const std::string&, const BenchmarkReporter*); DISALLOW_COPY_AND_ASSIGN(Benchmark); }; -// ------------------------------------------------------ -// Benchmarks reporter interface + data containers. - -struct BenchmarkContextData { - int num_cpus; - double mhz_per_cpu; - // std::string cpu_info; - bool cpu_scaling_enabled; - - // The number of chars in the longest benchmark name. - int name_field_width; -}; - -struct BenchmarkRunData { - BenchmarkRunData() - : thread_index(-1), - iterations(1), - real_accumulated_time(0), - cpu_accumulated_time(0), - bytes_per_second(0), - items_per_second(0), - max_heapbytes_used(0) {} - - std::string benchmark_name; - std::string report_label; - int thread_index; - int64_t iterations; - double real_accumulated_time; - double cpu_accumulated_time; - - // Zero if not set by benchmark. - double bytes_per_second; - double items_per_second; - - // This is set to 0.0 if memory tracing is not enabled. - double max_heapbytes_used; -}; - -// Interface for custom benchmark result printers. -// By default, benchmark reports are printed to stdout. However an application -// can control the destination of the reports by calling -// RunMatchingBenchmarks and passing it a custom reporter object. -// The reporter object must implement the following interface. -class BenchmarkReporter { - public: - // Called once for every suite of benchmarks run. - // The parameter "context" contains information that the - // reporter may wish to use when generating its report, for example the - // platform under which the benchmarks are running. The benchmark run is - // never started if this function returns false, allowing the reporter - // to skip runs based on the context information. - virtual bool ReportContext(const BenchmarkContextData& context) = 0; - - // Called once for each group of benchmark runs, gives information about - // cpu-time and heap memory usage during the benchmark run. - // Note that all the grouped benchmark runs should refer to the same - // benchmark, thus have the same name. - virtual void ReportRuns(const std::vector& report) = 0; - - virtual ~BenchmarkReporter(); -}; - // ------------------------------------------------------ // Internal implementation details follow; please ignore -// Given a collection of reports, computes their mean and stddev. -// REQUIRES: all runs in "reports" must be from the same benchmark. -void ComputeStats(const std::vector& reports, - BenchmarkRunData* mean_data, BenchmarkRunData* stddev_data); - // Simple reporter that outputs benchmark data to the console. This is the // default reporter used by RunSpecifiedBenchmarks(). class ConsoleReporter : public BenchmarkReporter { public: - virtual bool ReportContext(const BenchmarkContextData& context); - virtual void ReportRuns(const std::vector& reports); + virtual bool ReportContext(const Context& context) const; + virtual void ReportRuns(const std::vector& reports) const; private: - std::string PrintMemoryUsage(double bytes); - virtual void PrintRunData(const BenchmarkRunData& report); - int name_field_width_; + std::string PrintMemoryUsage(double bytes) const; + virtual void PrintRunData(const Run& report) const; + mutable int name_field_width_; }; } // end namespace internal - -void Initialize(int* argc, const char** argv); } // end namespace benchmark // ------------------------------------------------------ diff --git a/src/benchmark.cc b/src/benchmark.cc index 3ea1c5b6..e5781c92 100644 --- a/src/benchmark.cc +++ b/src/benchmark.cc @@ -1,3 +1,17 @@ +// Copyright 2014 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #include "benchmark/benchmark.h" #include "benchmark/macros.h" #include "colorprint.h" @@ -224,14 +238,11 @@ bool CpuScalingEnabled() { return false; } -} // namespace - -namespace internal { - -BenchmarkReporter::~BenchmarkReporter() {} - -void ComputeStats(const std::vector& reports, - BenchmarkRunData* mean_data, BenchmarkRunData* stddev_data) { +// Given a collection of reports, computes their mean and stddev. +// REQUIRES: all runs in "reports" must be from the same benchmark. +void ComputeStats(const std::vector& reports, + BenchmarkReporter::Run* mean_data, + BenchmarkReporter::Run* stddev_data) { // Accumulators. Stat1_d real_accumulated_time_stat; Stat1_d cpu_accumulated_time_stat; @@ -241,7 +252,7 @@ void ComputeStats(const std::vector& reports, Stat1MinMax_d max_heapbytes_used_stat; // Populate the accumulators. - for (std::vector::const_iterator it = reports.begin(); + for (std::vector::const_iterator it = reports.begin(); it != reports.end(); ++it) { CHECK_EQ(reports[0].benchmark_name, it->benchmark_name); real_accumulated_time_stat += @@ -282,16 +293,21 @@ void ComputeStats(const std::vector& reports, stddev_data->items_per_second = items_per_second_stat.StdDev(); stddev_data->max_heapbytes_used = max_heapbytes_used_stat.StdDev(); } +} // namespace -std::string ConsoleReporter::PrintMemoryUsage(double bytes) { - if (!get_memory_usage || bytes < 0.0) return ""; +namespace internal { + +std::string ConsoleReporter::PrintMemoryUsage(double bytes) const { + if (!get_memory_usage || bytes < 0.0) + return ""; std::stringstream ss; ss << " " << HumanReadableNumber(bytes) << "B peak-mem"; return ss.str(); } -bool ConsoleReporter::ReportContext(const BenchmarkContextData& context) { +bool ConsoleReporter::ReportContext( + const BenchmarkReporter::Context& context) const { name_field_width_ = context.name_field_width; std::cout << "Benchmarking on " << context.num_cpus << " X " @@ -319,8 +335,9 @@ bool ConsoleReporter::ReportContext(const BenchmarkContextData& context) { return true; } -void ConsoleReporter::ReportRuns(const std::vector& reports) { - for (std::vector::const_iterator it = reports.begin(); +void ConsoleReporter::ReportRuns( + const std::vector& reports) const { + for (std::vector::const_iterator it = reports.begin(); it != reports.end(); ++it) { CHECK_EQ(reports[0].benchmark_name, it->benchmark_name); PrintRunData(*it); @@ -329,15 +346,15 @@ void ConsoleReporter::ReportRuns(const std::vector& reports) { // We don't report aggregated data if there was a single run. if (reports.size() < 2) return; - BenchmarkRunData mean_data; - BenchmarkRunData stddev_data; - internal::ComputeStats(reports, &mean_data, &stddev_data); + BenchmarkReporter::Run mean_data; + BenchmarkReporter::Run stddev_data; + ComputeStats(reports, &mean_data, &stddev_data); PrintRunData(mean_data); PrintRunData(stddev_data); } -void ConsoleReporter::PrintRunData(const BenchmarkRunData& result) { +void ConsoleReporter::PrintRunData(const BenchmarkReporter::Run& result) const { // Format bytes per second std::string rate; if (result.bytes_per_second > 0) { @@ -363,13 +380,14 @@ void ConsoleReporter::PrintRunData(const BenchmarkRunData& result) { (result.cpu_accumulated_time * 1e9) / (static_cast(result.iterations))); ColorPrintf(COLOR_CYAN, "%10lld", result.iterations); - ColorPrintf(COLOR_DEFAULT, "%*s %*s %s%s\n", - 16, rate.c_str(), + ColorPrintf(COLOR_DEFAULT, "%*s %*s %s %s\n", + 13, rate.c_str(), 18, items.c_str(), result.report_label.c_str(), PrintMemoryUsage(result.max_heapbytes_used).c_str()); } +/* TODO(dominic) void MemoryUsage() { // if (benchmark_mc) { // benchmark_mc->Reset(); @@ -377,6 +395,7 @@ void MemoryUsage() { get_memory_usage = true; //} } +*/ void UseRealTime() { use_real_time = true; } @@ -542,7 +561,7 @@ struct State::SharedState { int stopping; // Number of threads that have entered STOPPING state int threads; // Number of total threads that are running concurrently ThreadStats stats; - std::vector runs; // accumulated runs + std::vector runs; // accumulated runs std::string label; explicit SharedState(const internal::Benchmark::Instance* b) @@ -766,7 +785,7 @@ void Benchmark::MeasureOverhead() { #endif } -void Benchmark::RunInstance(const Instance& b, BenchmarkReporter* br) { +void Benchmark::RunInstance(const Instance& b, const BenchmarkReporter* br) { use_real_time = false; running_benchmark = true; // get_memory_usage = FLAGS_gbenchmark_memory_usage; @@ -810,7 +829,7 @@ void Benchmark::RunInstance(const Instance& b, BenchmarkReporter* br) { */ running_benchmark = false; - for (internal::BenchmarkRunData& report : state.runs) { + for (BenchmarkReporter::Run& report : state.runs) { double seconds = (use_real_time ? report.real_accumulated_time : report.cpu_accumulated_time); report.benchmark_name = b.name; @@ -1006,8 +1025,7 @@ bool State::FinishInterval() { return true; } - internal::BenchmarkRunData data; - data.thread_index = thread_index; + BenchmarkReporter::Run data; data.iterations = iterations_; data.thread_index = thread_index; @@ -1094,8 +1112,7 @@ void* State::RunWrapper(void* arg) { namespace internal { void RunMatchingBenchmarks(const std::string& spec, - BenchmarkReporter* reporter) { - CHECK(reporter != NULL); + const BenchmarkReporter* reporter) { if (spec.empty()) return; std::vector benchmarks; @@ -1121,7 +1138,7 @@ void RunMatchingBenchmarks(const std::string& spec, } // Print header here - BenchmarkContextData context; + BenchmarkReporter::Context context; context.num_cpus = NumCPUs(); context.mhz_per_cpu = CyclesPerSecond() / 1000000.0f; // context.cpu_info = base::CompactCPUIDInfoString(); @@ -1145,12 +1162,12 @@ void FindMatchingBenchmarkNames(const std::string& spec, } // end namespace internal -void RunSpecifiedBenchmarks() { +void RunSpecifiedBenchmarks(const BenchmarkReporter* reporter /*= nullptr*/) { std::string spec = FLAGS_benchmark_filter; if (spec.empty() || spec == "all") spec = "."; // Regexp that matches all benchmarks internal::ConsoleReporter default_reporter; - internal::RunMatchingBenchmarks(spec, &default_reporter); + internal::RunMatchingBenchmarks(spec, reporter == nullptr ? &default_reporter : reporter); pthread_cond_destroy(&starting_cv); pthread_mutex_destroy(&starting_mutex); pthread_mutex_destroy(&benchmark_mutex); diff --git a/src/colorprint.cc b/src/colorprint.cc index 1e214d57..c604f83d 100644 --- a/src/colorprint.cc +++ b/src/colorprint.cc @@ -1,3 +1,17 @@ +// Copyright 2014 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #include "colorprint.h" #include diff --git a/src/commandlineflags.cc b/src/commandlineflags.cc index 1b6468d6..6ea80f25 100644 --- a/src/commandlineflags.cc +++ b/src/commandlineflags.cc @@ -1,3 +1,17 @@ +// Copyright 2014 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #include "commandlineflags.h" #include diff --git a/src/sleep.cc b/src/sleep.cc index bfa62c3f..f6d3ce81 100644 --- a/src/sleep.cc +++ b/src/sleep.cc @@ -1,3 +1,17 @@ +// Copyright 2014 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #include "sleep.h" #include diff --git a/src/sysinfo.cc b/src/sysinfo.cc index 8fdb1ae9..8fadf7e1 100644 --- a/src/sysinfo.cc +++ b/src/sysinfo.cc @@ -1,3 +1,17 @@ +// Copyright 2014 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #include "sysinfo.h" #include @@ -20,21 +34,18 @@ namespace benchmark { namespace { +const int64_t estimate_time_ms = 1000; pthread_once_t cpuinfo_init = PTHREAD_ONCE_INIT; double cpuinfo_cycles_per_second = 1.0; int cpuinfo_num_cpus = 1; // Conservative guess -static pthread_mutex_t cputimens_mutex; +pthread_mutex_t cputimens_mutex; // Helper function estimates cycles/sec by observing cycles elapsed during // sleep(). Using small sleep time decreases accuracy significantly. -int64_t EstimateCyclesPerSecond(const int estimate_time_ms) { - CHECK(estimate_time_ms > 0); - double multiplier = 1000.0 / (double)estimate_time_ms; // scale by this much - +int64_t EstimateCyclesPerSecond() { const int64_t start_ticks = cycleclock::Now(); SleepForMilliseconds(estimate_time_ms); - const int64_t guess = int64_t(multiplier * (cycleclock::Now() - start_ticks)); - return guess; + return cycleclock::Now() - start_ticks; } // Helper function for reading an int from a file. Returns true if successful @@ -99,9 +110,9 @@ void InitializeSystemInfo() { if (fd == -1) { perror(pname); if (!saw_mhz) { - cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000); + cpuinfo_cycles_per_second = EstimateCyclesPerSecond(); } - return; // TODO: use generic tester instead? + return; } double bogo_clock = 1.0; @@ -165,7 +176,7 @@ void InitializeSystemInfo() { cpuinfo_cycles_per_second = bogo_clock; } else { // If we don't even have bogomips, we'll use the slow estimation. - cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000); + cpuinfo_cycles_per_second = EstimateCyclesPerSecond(); } } if (num_cpus == 0) { @@ -201,7 +212,7 @@ void InitializeSystemInfo() { if (sysctlbyname(sysctl_path, &hz, &sz, NULL, 0) != 0) { fprintf(stderr, "Unable to determine clock rate from sysctl: %s: %s\n", sysctl_path, strerror(errno)); - cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000); + cpuinfo_cycles_per_second = EstimateCyclesPerSecond(); } else { cpuinfo_cycles_per_second = hz; } @@ -221,8 +232,8 @@ void InitializeSystemInfo() { "~MHz", NULL, &data, &data_size))) cpuinfo_cycles_per_second = (int64)data * (int64)(1000 * 1000); // was mhz else - cpuinfo_cycles_per_second = EstimateCyclesPerSecond(500); // TODO <500? - // TODO: also figure out cpuinfo_num_cpus + cpuinfo_cycles_per_second = EstimateCyclesPerSecond(); + // TODO: also figure out cpuinfo_num_cpus #elif defined OS_MACOSX // returning "mach time units" per second. the current number of elapsed @@ -250,7 +261,7 @@ void InitializeSystemInfo() { #else // Generic cycles per second counter - cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000); + cpuinfo_cycles_per_second = EstimateCyclesPerSecond(); #endif } } // end namespace diff --git a/src/walltime.cc b/src/walltime.cc index b07525ce..b57913b2 100644 --- a/src/walltime.cc +++ b/src/walltime.cc @@ -1,3 +1,17 @@ +// Copyright 2014 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #include "walltime.h" #include