Celero - C++基准测试框架

网友投稿 737 2022-10-18

Celero - C++基准测试框架

Celero - C++基准测试框架

Celero

C++ Benchmarking Library

Copyright 2017-2019 John Farrier

Apache 2.0 License

Community Support

A Special Thanks to the following corporations for their support:

Hellebore Consulting GroupAraxisAxosoftMicrosoftTravis.CI

Builds and Testing

Celero has been successfully built on the following platforms during development. See Travis.CI for more details.

GCC v6.0.0GCC v7.0.0GCC v8.0.0LLVM v3.9.0LLVM v5.0.1LLVM v7.0.0LLVM v8.0.0Visual Studio 2017Visual Studio 2019XCode v10.1XCode v10.3XCode v11.0

Quality Control

Overview

Developing consistent and meaningful benchmark results for code is a complicated task. Measurement tools exist (Intel® VTune™ Amplifier, SmartBear AQTime, Valgrind, etc.) external to applications, but they are sometimes expensive for small teams or cumbersome to utilize. This project, Celero, aims to be a small library which can be added to a C++ project and perform benchmarks on code in a way which is easy to reproduce, share, and compare among individual runs, developers, or projects. Celero uses a framework similar to that of GoogleTest to make its API more natural to use and integrate into a project. Make automated benchmarking as much a part of your development process as automated testing.

Celero uses CMake to provide cross-platform builds. It does require a modern compiler (Visual C++ 2012+, GCC 4.7+, Clang 2.9+) due to its use of C++11.

Once Celero is added to your project. You can create dedicated benchmark projects and source files. For convenience, there is single header file and a CELERO_MAIN macro that can be used to provide a main() for your benchmark project that will automatically execute all of your benchmark tests.

Key Features

Supports Windows, Linux, and OSX using C++11.The timing utilities can be used directly in production code (independent of benchmarks).Console table output is formatted as Markdown to easily copy/paste into documents.Archive results to track performance over time.Integrates into CI/CT/CD environments with JUnit-formatted output.User-defined Experiment Values can scale test results, sample sizes, and user-defined properties for each run.User-defined Measurements allow for measuring anything in addition to timing.Supports Test Fixtures.Supports fixed-time benchmark baselines.Capture a rich set of timing statistics to a file.Easily installed using CMake, Conan, or VCPkg.

Command Line

[-g groupNameToRun] [-t resultsTable.csv] [-j junitOutputFile.xml] [-a resultArchive.csv] [-d numberOfIterationsPerDistribution] [-h]

-g Use this option to run only one benchmark group out of all benchmarks contained within a test executable.-t Writes all results to a CSV file. Very useful when using problem sets to graph performance.-j Writes JUnit formatted XML output. To utilize JUnit output, benchmarks must use the _TEST version of the macros and specify an expected baseline multiple. When the test exceeds this multiple, the JUnit output will indicate a failure.-a Builds or updates an archive of historical results, tracking current, best, and worst results for each benchmark.-d (Experimental) builds a plot of four different sample sizes to investigate the distribution of sample results.

Celero Basics

Background

The goal, generally, of writing benchmarks is to measure the performance of a piece of code. Benchmarks are useful for comparing multiple solutions to the same problem to select the most appropriate one. Other times, benchmarks can highlight the performance impact of design or algorithm changes and quantify them in a meaningful way.

By measuring code performance, you eliminate errors in your assumptions about what the "right" solution is for performance. Only through measurement can you confirm that using a lookup table, for example, is faster than computing a value. Such lore (which is often repeated) can lead to bad design decisions and, ultimately, slower code.

The goal of writing correct benchmarking code is to eliminate all of the noise and overhead, and measure just the code under test. Sources of noise in the measurements include clock resolution noise, operating system background operations, test setup/teardown, framework overhead, and other unrelated system activity.

At a theoretical level, we want to measure "t," the time to execute the code under test. In reality, we measure "t" plus all of this measurement noise.

These extraneous contributors to our measurement of "t" fluctuate over time. Therefore, we want to try to isolate "t'. The way this is accomplished is by making many measurements, but only keeping the smallest total. The smallest total is necessarily the one with the smallest noise contribution and closest to the actual time "t."

Once this measurement is obtained, it has little meaning in isolation. It is essential to create a baseline test by which to compare. A baseline should generally be a "classic" or "pure" solution to the problem on which you measure a solution. Once you have a baseline, you have a meaningful time to compare your algorithm against. Merely saying that your fancy sorting algorithm (fSort) sorted a million elements in 10 milliseconds is not sufficient by itself. However, compare that to a classic sorting algorithm baseline such as quicksort (qSort) and then you can say that fSort is 50% faster than qSort on a million elements. That is a meaningful and powerful measurement.

Implementation

Celero heavily utilizes C++11 features that are available in both Visual C++ 2012 and GCC 4.7. C++11 greatly aided in making the code clean and portable. To make adopting the code more manageable, all definitions needed by a user are defined in a celero namespace within a single include file: Celero.h.

Celero.h has within it the macro definitions that turn each of the user benchmark cases into its own unique class with the associated test fixture (if any) and then registers the test case within a Factory. The macros automatically associate baseline test cases with their associated test benchmarks so that, at run time, benchmark-relative numbers can be computed. This association is maintained by TestVector.

The TestVector utilizes the PImpl idiom to help hide implementation and keep the include overhead of Celero.h to a minimum.

Celero reports its outputs to the command line. Since colors are nice (and perhaps contribute to the human factors/readability of the results), something beyond std::cout was called for. Console.h defines a simple color function, SetConsoleColor, which is utilized by the functions in the celero::print namespace to nicely format the program's output.

Measuring benchmark execution time takes place in the TestFixture base class, from which all benchmarks are written are ultimately derived. First, the test fixture setup code is executed. Then, the start time for the test is retrieved and stored in microseconds using an unsigned long. This is done to reduce floating point error. Next, the specified number of operations (iterations) is executed. When complete, the end time is retrieved, the test fixture is torn down, and the measured time for the execution is returned, and the results are saved.

This cycle is repeated for however-many samples were specified. If no samples were specified (zero), then the test is repeated until it as ran for at least one second or at least 30 samples have been taken. While writing this specific part of the code, there was a definite "if-else" relationship. However, the bulk of the code was repeated within the "if" and "else" sections. An old fashioned function could have been used here, but it was very natural to utilize std::function to define a lambda that could be called and keep all of the code clean. (C++11 is a fantastic thing.) Finally, the results are printed to the screen.

General Program Flow

To summarize, this pseudo-code illustrates how the tests are executed internally:

for(Each Experiment){ for(Each Sample) { // Call the virtual function // and DO NOT include its time in the measurement. experiment->setUp(); // Start the Timer timer->start(); // Run all iterations for(Each Iteration) { // Call the virtual function // and include its time in the measurement. experiment->onExperimentStart(x); // Run the code under test experiment->run(threads, iterations, experimentValue); // Call the virtual function // and include its time in the measurement. experiment->onExperimentEnd(); } // Stop the Timer timer->stop(); // Record data... // Call the virtual teardown function // and DO NOT include its time in the measurement. experiment->tearDown(); }}

Using the Code

Celero uses CMake to provide cross-platform builds. It does require a modern compiler (Visual C++ 2012 or GCC 4.7+) due to its use of C++11.

Once Celero is added to your project. You can create dedicated benchmark projects and source files. For convenience, there is single header file and a CELERO_MAIN macro that can be used to provide a main() for your benchmark project that will automatically execute all of your benchmark tests.

Here is an example of a simple Celero Benchmark. (Note: This is a complete, runnable example.)

#include #include #ifndef WIN32#include #include #endif////// This is the main(int argc, char** argv) for the entire celero program./// You can write your own, or use this macro to insert the standard one into the project.///CELERO_MAINstd::random_device RandomDevice;std::uniform_int_distribution UniformDistribution(0, 1024);////// In reality, all of the "Complex" cases take the same amount of time to run./// The difference in the results is a product of measurement error.////// Interestingly, taking the sin of a constant number here resulted in a/// great deal of optimization in clang and gcc.///BASELINE(DemoSimple, Baseline, 10, 1000000){ celero::DoNotOptimizeAway(static_cast(sin(UniformDistribution(RandomDevice))));}////// Run a test consisting of 1 sample of 710000 operations per measurement./// There are not enough samples here to likely get a meaningful result.///BENCHMARK(DemoSimple, Complex1, 1, 710000){ celero::DoNotOptimizeAway(static_cast(sin(fmod(UniformDistribution(RandomDevice), 3.14159265))));}////// Run a test consisting of 30 samples of 710000 operations per measurement./// There are not enough samples here to get a reasonable measurement/// It should get a Baseline number lower than the previous test.///BENCHMARK(DemoSimple, Complex2, 30, 710000){ celero::DoNotOptimizeAway(static_cast(sin(fmod(UniformDistribution(RandomDevice), 3.14159265))));}////// Run a test consisting of 60 samples of 710000 operations per measurement./// There are not enough samples here to get a reasonable measurement/// It should get a Baseline number lower than the previous test.///BENCHMARK(DemoSimple, Complex3, 60, 710000){ celero::DoNotOptimizeAway(static_cast(sin(fmod(UniformDistribution(RandomDevice), 3.14159265))));}

The first thing we do in this code is to define a BASELINE test case. This template takes four arguments:

BASELINE(GroupName, BaselineName, Samples, Operations)

GroupName - The name of the benchmark group. This is used to batch together runs and results with their corresponding baseline measurement.BaselineName - The name of this baseline for reporting purposes.Samples - The total number of times you want to execute the given number of operations on the test code.Operations - The total number of times you want to run the test code per sample.

Samples and operations here are used to measure very fast code. If you know the code in your benchmark will take some time less than 100 milliseconds, for example, your operations number would say to execute the code "operations" number of times before taking a measurement. Samples define how many measurements to make.

Celero helps with this by allowing you to specify zero samples. Zero samples will tell Celero to make some statistically significant number of samples based on how long it takes to complete your specified number of operations. These numbers will be reported at run time.

The celero::DoNotOptimizeAway template is provided to ensure that the optimizing compiler does not eliminate your function or code. Since this feature is used in all of the sample benchmarks and their baseline, it's time overhead is canceled out in the comparisons.

After the baseline is defined, various benchmarks are then defined. The syntax for the BENCHMARK macro is identical to that of the macro.

Results

Running Celero's simple example experiment (celeroDemoSimple.exe) benchmark gave the following output on a PC:

CeleroTimer resolution: 0.277056 us| Group | Experiment | Prob. Space | Samples | Iterations | Baseline | us/Iteration | Iterations/sec ||:--------------:|:---------------:|:---------------:|:---------------:|:---------------:|:---------------:|:---------------:|:---------------:||DemoSimple | Baseline | Null | 30 | 1000000 | 1.00000 | 0.09320 | 10729498.61 ||DemoSimple | Complex1 | Null | 1 | 710000 | 0.99833 | 0.09305 | 10747479.64 ||DemoSimple | Complex2 | Null | 30 | 710000 | 0.97898 | 0.09124 | 10959834.52 ||DemoSimple | Complex3 | Null | 60 | 710000 | 0.98547 | 0.09185 | 10887733.66 |Completed in 00:00:10.315012

The first test that executes will be the group's baseline. Celero took 30 samples of 1000000 iterations of the code in our test. (Each set of 1000000 iterations was measured, and this was done ten times and the shortest time was taken.) The "Baseline" value for the baseline measurement itself will always be 1.0.

After the baseline is complete, each individual test runs. Each test is executed and measured in the same way. However, there is an additional metric reported: Baseline. This compares the time it takes to compute the benchmark to the baseline. The data here shows that CeleroBenchTest.Complex1 takes 1.007949 times longer to execute than the baseline.

Automatically computing the number of Iterations and Samples

If you do want Celero to figure out a reasonable number of iterations to run, you can set the iteration value to 0 for your experiment. You can also set the number of samples to 0 to have it compute a statistically valid number of samples. (Note that the current implementation uses 30 as the default number of samples, but does calculate a reasonable number of iterations.)

Update the previous "DemoSimple" code's Complex1 case to use this feature as follows:

/// Run a test consisting of 0 samples of 0 iterations per measurement./// Since the sample size is equal to 0, celero will compute a number to use for both samples and iterations.BENCHMARK(DemoSimple, Complex1, 0, 0){ celero::DoNotOptimizeAway(static_cast(sin(fmod(UniformDistribution(RandomDevice), 3.14159265))));}

Now, when this executes, you will see a different number automatically computed for the number of iterations, and the sample size has been increased.

CeleroTimer resolution: 0.277056 us| Group | Experiment | Prob. Space | Samples | Iterations | Baseline | us/Iteration | Iterations/sec ||:--------------:|:---------------:|:---------------:|:---------------:|:---------------:|:---------------:|:---------------:|:---------------:||DemoSimple | Baseline | Null | 30 | 1000000 | 1.00000 | 0.09177 | 10897044.72 ||DemoSimple | Complex1 | Null | 30 | 8388608 | 1.01211 | 0.09288 | 10766703.67 ||DemoSimple | Complex2 | Null | 30 | 710000 | 0.99559 | 0.09136 | 10945304.31 ||DemoSimple | Complex3 | Null | 60 | 710000 | 0.99671 | 0.09147 | 10933000.72 |Completed in 00:00:37.583872

Statistically Sound Results

To use Celero for real science, there are three primary factors to consider when reviewing results. Firstly, you MUST check the generated assembly for your test. There are different paths to viewing the assembly for various compilers, but essentially this must be done to ensure that you did not optimize-out critical code. You must also verify, via assembly, that you are comparing apples to apples.

Once that is sorted out, you should run just the "Baseline" case several times. The "us/Iteration" and "Iterations/sec" should not fluctuate by any significant degree between runs. If they do, then ensure that your number of iterations is sufficiently large as to overcome the timer resolution on your machine. Once the number of iterations is high enough, ensure that you are performing a statistically significant number of samples. Lore has it that 30 samples are good, but use your own science to figure out the best number for your situation.

Finally, you need to ensure that the number of iterations and samples is producing stable output for your experiment cases. These numbers may be the same as your now-stable baseline case.

One factor that can impact the number of samples and iterations required is the amount of work that your experiment is doing. For cases where you are utilizing Celero's "problem space" functionality to scale up the algorithms, you can correspondingly scale down the number of iterations. Doing so can reduce the total run time of the more extensive experiments by doing fewer iterations, buy while still maintaining a statistically meaningful measurement. (It saves you time.)

Threaded Benchmarks

Celero can automatically run threaded benchmarks. BASELINE_T and BENCHMARK_T can be used to launch the given code on its own thread using a user-defined number of concurrent executions. celeroDemoMultithread illustrates using this feature. When defining these macros, they use the following format:

BASELINE_T(groupName, baselineName, fixtureName, samples, iterations, threads);BASELINE_FIXED_T(groupName, baselineName, fixtureName, samples, iterations, threads, useconds);BENCHMARK_T(groupName, benchmarkName, fixtureName, samples, iterations, threads);BENCHMARK_TEST_T(groupName, benchmarkName, fixtureName, samples, iterations, threads, target);

Fixed Measurement Benchmarks

While Celero typically measures the baseline time and then executes benchmark cases for comparison, you can also specify a fixed measurement time. This is useful for measuring performance against a real-time requirement. To use, utilize the _FIXED_ version of the BASELINE and BENCHMARK macros.

// No threads or test fixtures.BASELINE_FIXED(groupName, baselineName, samples, iterations, useconds);// For using test fixtures:BASELINE_FIXED_F(groupName, baselineName, fixtureName, samples, iterations, useconds);// For using threads and test fixtures.BASELINE_FIXED_T(groupName, baselineName, fixtureName, samples, iterations, threads, useconds);

Example:

BASELINE_FIXED_F(DemoTransform, FixedTime, DemoTransformFixture, 30, 10000, 100){ /* Nothing to do */ }

User-Defined Measurements (UDM)

Celero, by default, measures the execution time of your experiments. If you want to measure anything else, say for example the number of page faults via PAPI, user-defined measurements are for you.

Adding user-defined measurements consists of three steps:

Define a class for your user-defined measurement. (One per type of measurement.) This class must derive from celero::UserDefinedMeasurement. Celero provides a convenience class celero::UserDefinedMeasurementTemplate<> which will be sufficient for most uses.Add (an) instance(s) of your class(es) to your test fixture. Implement getUserDefinedMeasurements to return these instances.At the appropriate point (most likely tearDown()), record your measurements in your user-defined measurement instances.

As a rough example, say you want to measure the number of page faults. The class for your user-defined measurement could be as simple as this:

class PageFaultUDM : public celero::UserDefinedMeasurementTemplate{ virtual std::string getName() const override { return "Page Faults"; } // Optionally turn off some statistical reporting. virtual bool reportKurtosis() const override { return false; }};

The only thing you need to implement in this case is a unique name. Other virtual functions are available inside celero::UserDefinedMeasurementTemplate and celero::UserDefinedMeasurement that you can leverage as needed. There are optional virtual functions that you can override to turn off specific statistical measurements in the output. These are:

virtual bool reportSize() const; virtual bool reportMean() const; virtual bool reportVariance() const; virtual bool reportStandardDeviation() const; virtual bool reportSkewness() const; virtual bool reportKurtosis() const; virtual bool reportZScore() const; virtual bool reportMin() const; virtual bool reportMax() const;

(By default, all of the report functions inside UserDefinedMeasurementTemplate return true.)

Now, add it to your regular Celero test fixure:

class SortFixture : public celero::TestFixture{public: SortFixture() { this->pageFaultUDM.reset(new PageFaultUDM()); } [...] virtual std::vector> getUserDefinedMeasurements() const override { return { this->pageFaultUDM }; }private: std::shared_ptr pageFaultUDM;};

Finally, you need to record your results. For this pseud-code example, assume two functions exist: resetPageFaultCounter() and getPageFaults(). These reset the number of page faults and return the number of page faults since last reset, respectively. Then, add these to the setUp and tearDown methods:

class SortFixture : public celero::TestFixture{public: SortFixture() { this->pageFaultUDM.reset(new PageFaultUDM()); } [...] // Gather page fault statistics inside the UDM. virtual void onExperimentEnd() override { [...] this->pageFaultUDM->addValue(this->getPageFaults()); } [...] // Reset the page fault counter. virtual void setUp(const celero::TestFixture::ExperimentValue& experimentValue) override { [...] this->resetPageFaultCounter(); } [...] virtual std::vector> getUserDefinedMeasurements() const override { return { this->pageFaultUDM }; }private: std::shared_ptr pageFaultUDM; [...]};

You will now be reporting statistics on the number of page faults that occurred during your experiments. See the ExperimentSortingRandomIntsWithUDM example for a complete example.

A note on User-Defined Measurements: This capability was introduced well after the creation of Celero. While it is a great enhancement to the library, it was not designed-in to the library. As such, the next major release of the library (v3.x) may change the way this is implemented and exposed to the library's users.

Frequency Scaling

CPU Frequency Scaling should be disabled if possible when executing benchmarks. While there is code in Celero to attempt to do this, it may not have sufficient privileges to be effective. On Linux systems, this can be accomplished as follows:

sudo cpupower frequency-set --governor performance./celeroBenchmarkExecutablesudo cpupower frequency-set --governor powersave

Notes

Benchmarks should always be performed on Release builds. Never measure the performance of a Debug build and make changes based on the results. The (optimizing) compiler is your friend concerning code performance.Accuracy is tied very closely to the total number of samples and the sample sizes. As a general rule, you should aim to execute your baseline code for about as long as your longest benchmark test. Further, it is helpful if all of the benchmark tests take about the same order of magnitude of execution time. (Don't compare a baseline that executed in 0.1 seconds with benchmarks that take 60 seconds and an hour, respectively.)Celero has Doxygen documentation of its API.Celero supports test fixtures for each baseline group.

Celero Charts

Background

It has been noted many times that writing an algorithm to solve small problems is relatively easy. "Brute force" methods tend to function just as well as more agile approaches. However, as the size of data increases, beneficial algorithms scale their performance to match.

Theoretically, the best we can hope for with an algorithm is that is scales linearly (Order N, O(N) complexity) with respect to the problem size. That is to say that if the problem set doubles, the time it takes for the algorithm to execute doubles. While this seems obvious, it is often an elusive goal.

Even well-performing algorithms eventually run into problems with available memory or CPU cache. When making decisions within our software about algorithms and improvements to existing code, only through measurement and experimentation, can we know our complex algorithms perform acceptably.

Using the Code

While Celero offers simple benchmarking of code and algorithms, it also provides a more sophisticated method or directly producing performance graphs of how the benchmarks change with respect to some independent variable, referred to here as the Problem Set.

Within Celero, a test fixture can push integers into a ProblemSetValues vector which allows for the fixture's own SetUp function to scale a problem set for the benchmarks to run against. For each value pushed into the ProblemSetValues vector, a complete set of benchmarks is executed. These measured values are then stored and can be written out to a CSV file for easy plotting of results.

To demonstrate, we will study the performance of three common sorting algorithms: BubbleSort, SelectionSort, and std::sort. (The source code to this demo is distributed with Celero, available on GitHub.) First, we will write a test fixture for Celero.

class SortFixture : public celero::TestFixture{public: SortFixture() { } virtual std::vector getExperimentValues() const override { std::vector problemSpace; // We will run some total number of sets of tests together. // Each one growing by a power of 2. const int totalNumberOfTests = 6; for(int i = 0; i < totalNumberOfTests; i++) { // ExperimentValues is part of the base class and allows us to specify // some values to control various test runs to end up building a nice graph. problemSpace.push_back({int64_t(pow(2, i+1))}); } return problemSpace; } /// Before each run, build a vector of random integers. virtual void setUp(const celero::TestFixture::ExperimentValue& experimentValue) { this->arraySize = experimentValue.Value; this->array.reserve(this->arraySize); } /// Before each iteration. A common utility function to push back random ints to sort. void randomize() { for(int i = 0; i < this->arraySize; i++) { this->array.push_back(rand()); } } /// After each iteration, clear the vector of random integers. void clear() { this->array.clear(); } std::vector array; int64_t arraySize;};

Before the test fixture is utilized by a benchmark, Celero will create an instantiation of the class and call its getExperimentValues() function. The test fixture can then build a vector of TestFixture::ExperimentValue values. For each value added to this array, benchmarks will be executed following calls to the setUp virtual function. A new test fixture is created for each measurement.

The SetUp() virtual function is called before each benchmark test is executed. When using a problem space values vector, the function will be given a value that was previously pushed into the array within the constructor. The function's code can then decide what to do with it. Here, we are using the value to indicate how many elements should be in the array that we intend to sort. For each of the array elements, we simply add a pseudo-random integer.

Now for implementing the actual sorting algorithms. For the baseline case, I implemented the first sorting algorithm I ever learned in school: Bubble Sort. The code for bubble sort is straight forward.

// For a baseline, I'll choose Bubble Sort.BASELINE_F(SortRandInts, BubbleSort, SortFixture, 30, 10000){ this->randomize(); for(int x = 0; x < this->arraySize; x++) { for(int y = 0; y < this->arraySize - 1; y++) { if(this->array[y] > this->array[y+1]) { std::swap(this->array[y], this->array[y+1]); } } } this->clear();}

Celero will use the values from this baseline when computing a base lined measurement for the other two algorithms in the test group DemoSort. However, when we run this at the command line, we will specify an output file. The output file will contain the measured number of seconds the algorithm took to execute on the given array size.

Next, we will implement the Selection Sort algorithm.

BENCHMARK_F(SortRandInts, SelectionSort, SortFixture, 30, 10000){ this->randomize(); for(int x = 0; x < this->arraySize; x++) { auto minIdx = x; for(int y = x; y < this->arraySize; y++) { if(this->array[minIdx] > this->array[y]) { minIdx = y; } } std::swap(this->array[x], this->array[minIdx]); } this->clear();}

Finally, for good measure, we will simply use the Standard Library's sorting algorithm: Introsort. We only need to write a single line of code, but here it is for completeness.

BENCHMARK_F(SortRandInts, stdSort, SortFixture, 30, 10000){ this->randomize(); std::sort(this->array.begin(), this->array.end()); this->clear();}

Results

This test was run on a 4.00 GHz AMD with four cores, eight logical processors, and 32 GB of memory. (Hardware aside, the relative performance of these algorithms should be the same on any modern hardware.)

Celero outputs timing and benchmark references for each test automatically. However, to write to an output file for easy plotting, simply specify an output file on the command line.

celeroExperimentSortingRandomInts.exe -t results.csv

While not particularly surprising std::sort is by far the best option with any meaningful problem set size. The results are summarized in the following table output written directly by Celero:

CeleroCelero: CPU processor throttling disabled.Timer resolution: 0.254288 usWriting results to: results.csv----------------------------------------------------------------------------------------------------------------------------------------------- Group | Experiment | Prob. Space | Samples | Iterations | Baseline | us/Iteration | Iterations/sec |-----------------------------------------------------------------------------------------------------------------------------------------------SortRandInts | BubbleSort | 2 | 30 | 10000 | 1.00000 | 0.05270 | 18975332.07 |SortRandInts | BubbleSort | 4 | 30 | 10000 | 1.00000 | 0.12060 | 8291873.96 |SortRandInts | BubbleSort | 8 | 30 | 10000 | 1.00000 | 0.31420 | 3182686.19 |SortRandInts | BubbleSort | 16 | 30 | 10000 | 1.00000 | 1.09130 | 916338.31 |SortRandInts | BubbleSort | 32 | 30 | 10000 | 1.00000 | 3.23470 | 309147.68 |SortRandInts | BubbleSort | 64 | 30 | 10000 | 1.00000 | 10.82530 | 92376.19 |SortRandInts | SelectionSort | 2 | 30 | 10000 | 1.09108 | 0.05750 | 17391304.35 |SortRandInts | SelectionSort | 4 | 30 | 10000 | 1.03317 | 0.12460 | 8025682.18 |SortRandInts | SelectionSort | 8 | 30 | 10000 | 1.01464 | 0.31880 | 3136762.86 |SortRandInts | SelectionSort | 16 | 30 | 10000 | 0.72253 | 0.78850 | 1268230.82 |SortRandInts | SelectionSort | 32 | 30 | 10000 | 0.63771 | 2.06280 | 484777.97 |SortRandInts | SelectionSort | 64 | 30 | 10000 | 0.54703 | 5.92180 | 168867.57 |SortRandInts | InsertionSort | 2 | 30 | 10000 | 1.07021 | 0.05640 | 17730496.45 |SortRandInts | InsertionSort | 4 | 30 | 10000 | 1.05970 | 0.12780 | 7824726.13 |SortRandInts | InsertionSort | 8 | 30 | 10000 | 1.00382 | 0.31540 | 3170577.05 |SortRandInts | InsertionSort | 16 | 30 | 10000 | 0.74104 | 0.80870 | 1236552.49 |SortRandInts | InsertionSort | 32 | 30 | 10000 | 0.61508 | 1.98960 | 502613.59 |SortRandInts | InsertionSort | 64 | 30 | 10000 | 0.45097 | 4.88190 | 204838.28 |SortRandInts | QuickSort | 2 | 30 | 10000 | 1.18027 | 0.06220 | 16077170.42 |SortRandInts | QuickSort | 4 | 30 | 10000 | 1.16169 | 0.14010 | 7137758.74 |SortRandInts | QuickSort | 8 | 30 | 10000 | 1.01400 | 0.31860 | 3138731.95 |SortRandInts | QuickSort | 16 | 30 | 10000 | 0.65060 | 0.71000 | 1408450.70 |SortRandInts | QuickSort | 32 | 30 | 10000 | 0.48542 | 1.57020 | 636861.55 |SortRandInts | QuickSort | 64 | 30 | 10000 | 0.34431 | 3.72730 | 268290.72 |SortRandInts | stdSort | 2 | 30 | 10000 | 1.08539 | 0.05720 | 17482517.48 |SortRandInts | stdSort | 4 | 30 | 10000 | 0.94776 | 0.11430 | 8748906.39 |SortRandInts | stdSort | 8 | 30 | 10000 | 0.76926 | 0.24170 | 4137360.36 |SortRandInts | stdSort | 16 | 30 | 10000 | 0.45954 | 0.50150 | 1994017.95 |SortRandInts | stdSort | 32 | 30 | 10000 | 0.33573 | 1.08600 | 920810.31 |SortRandInts | stdSort | 64 | 30 | 10000 | 0.23979 | 2.59580 | 385237.69 |

The data shows first the test group name. Next, all of the data sizes are output. Then each row shows the baseline or benchmark name and the corresponding time for the algorithm to complete measured in useconds. This data, in CSV format, can be directly read by programs such as Microsoft Excel and plotted without any modification. The CSV contains the following data:

GroupExperimentProblem SpaceSamplesIterationsBaselineus/IterationIterations/secMin (us)Mean (us)Max (us)VarianceStandard DeviationSkewnessKurtosisZ Score
SortRandIntsBubbleSort2301000010.05271.89753e+07527532.533582118.7410.89683.6431613.07260.507794
SortRandIntsBubbleSort4301000010.12068.29187e+0612061230.7714551941.2244.05934.6005620.95420.562122
SortRandIntsBubbleSort8301000010.31423.18269e+0631423195.7334253080.4155.50142.483837.726050.968143
SortRandIntsBubbleSort16301000011.09139163381091311022.1112285450.2673.82590.717780.3874411.47825
SortRandIntsBubbleSort32301000013.23473091483234732803.936732650545806.5634.123617.26160.566519
SortRandIntsBubbleSort643010000110.825392376.21082531109991333892.8152e+075305.853.154559.602460.517542
SortRandIntsSelectionSort230100001.091080.05751.73913e+07575620.1677532170.9746.59371.337941.198710.969373
SortRandIntsSelectionSort430100001.033170.12468.02568e+0612461339.5714132261.747.5574-0.263592-0.7276211.96745
SortRandIntsSelectionSort830100001.014640.31883.13676e+0631883500.63374220181.2142.061-0.438792-0.5223542.2007
SortRandIntsSelectionSort1630100000.7225330.78851.26823e+0678858504.679482322584567.9650.274438-1.437411.09103
SortRandIntsSelectionSort3230100000.637712.06284847782062820826.72137826307.7162.1961.644312.962391.22526
SortRandIntsSelectionSort6430100000.5470335.92181688685921859517.76030855879.5236.3891.424192.383411.26783
SortRandIntsInsertionSort230100001.070210.05641.77305e+07564585.48142239.4247.32254.0686816.62540.452216
SortRandIntsInsertionSort430100001.05970.12787.82473e+061278131215743857.1762.10613.067919.387060.54745
SortRandIntsInsertionSort830100001.003820.31543.17058e+0631543208.5736178053.9189.74363.4064912.51610.608029
SortRandIntsInsertionSort1630100000.7410430.80871.23655e+0680878198.43855611392.8106.7371.669843.104171.044
SortRandIntsInsertionSort3230100000.615081.98965026141989620088.92059320955.8144.7611.978184.122961.33254
SortRandIntsInsertionSort6430100000.4509714.8819204838488194915250253129327359.621.75832.515880.925884
SortRandIntsQuickSort230100001.180270.06221.60772e+07622647.48362492.5249.92522.836287.088360.508761
SortRandIntsQuickSort430100001.161690.14017.13776e+061401145016554476.2166.90451.945382.903630.732388
SortRandIntsQuickSort830100001.0140.31863.13873e+0631863245.835495043.8971.02032.883969.362310.842012
SortRandIntsQuickSort1630100000.65060.711.40845e+0671007231.07767017248.2131.3321.938583.210110.997977
SortRandIntsQuickSort3230100000.4854241.57026368621570215863.21646933518183.0792.018333.27630.880494
SortRandIntsQuickSort6430100000.3443143.72732682913727337554.43799934113.3184.6980.822276-0.01866331.52339
SortRandIntsstdSort230100001.085390.05721.74825e+07572591.2337641863.1543.16422.868757.639240.445585
SortRandIntsstdSort430100000.9477610.11438.74891e+0611431185.3313853435.458.61232.532775.698260.72226
SortRandIntsstdSort830100000.7692550.24174.13736e+0624172459.4728386555.8480.96823.7813214.52640.524486
SortRandIntsstdSort1630100000.4595440.50151.99402e+0650155120.9752836486.6580.53980.55161-0.7986511.31571
SortRandIntsstdSort3230100000.3357341.0869208101086013398245928.85889e+062976.392.15974.932410.852722
SortRandIntsstdSort6430100000.239792.59583852382595827384.8358004.88819e+062210.922.246325.154220.645326

The point here is not that std::sort is better than more elementary sorting methods, but how easily measurable results can be obtained. In making such measurements more accessible and easier to code, they can become part of the way we code just as automated testing has become.

Test early and test often!

Notes

Because I like explicitness as much as the next programmer, I want to note that the actual sorting algorithm used by std::sort is not defined in the standard, but references cite Introsort as a likely contender for how an STL implementation would approach std::sort. Wikipedia.When choosing a sorting algorithm, start with std::sort and see if you can make improvements from there.Don't just trust your experience, measure your code!

FAQ

Q: I asked for N iterations, but Celero ran N+1 iterations.

The internal code will do one un-measured "warm-up" pass. This helps account for caching which may otherwise influence measurements.

Q: As my problem space increases in size, my runs take longer and longer. How do I account for the increased complexity?

When defining a problem space, you set up a celero::TestFixture::ExperimentValue. If the Iterations member in the class is greater than zero, that number will be used to control the amount of iterations for the corresponding celero::TestFixture::ExperimentValue.

class MyFixture : public celero::TestFixture{public: virtual std::vector> getExperimentValues() const override { std::vector> problemSpaceValues; // We will run some total number of sets of tests together. // Each one growing by a power of 2. const int totalNumberOfTests = 12; for(int i = 0; i < totalNumberOfTests; i++) { // ExperimentValues is part of the base class and allows us to specify // some values to control various test runs to end up building a nice graph. // We make the number of iterations decrease as the size of our problem space increases // to demonstrate how to adjust the number of iterations per sample based on the // problem space size. problemSpaceValues.push_back(std::make_pair(int64_t(pow(2, i + 1)), uint64_t(pow(2, totalNumberOfTests - i)))); } return problemSpaceValues; }

Example and Demo Code

Example and demonstration code are provided under Celero's "experiments" folder. There are two types of projects. The first is "Demo" projects. These are useful for illustrating techniques and ideas, but may not be interesting from a computer-science perspective. Experiments, on the other hand, have been added which demonstrate real-world questions.

The addition of real use cases of Celero is encouraged to be submitted to Celero's development branch for inclusion in the Demo and Experiment library.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Qt带进度条的启动界面
下一篇:光说不练假把式,一起Kafka业务实战。
相关文章

 发表评论

暂时没有评论,来抢沙发吧~