Created
November 12, 2020 12:23
-
-
Save kd9f9/71ceaefbcab435d51c5a929b988e768a to your computer and use it in GitHub Desktop.
code for the post https://cppbenchmarks.wordpress.com/2020/11/10/float-division-vs-multiplication-speed/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// source code for the post https://cppbenchmarks.wordpress.com/2020/11/10/float-division-vs-multiplication-speed/ | |
#include <array> | |
#include <chrono> | |
#include <numeric> | |
#include <iostream> | |
float doNotOptimizeAway = 0.0F; | |
template <int nElements> std::chrono::microseconds benchmarkMultiplicationF32() { | |
srand(0); | |
std::array<float, nElements> data; | |
for (int i = 0; i < nElements; ++i) { | |
data[i] = rand(); | |
} | |
const auto start = std::chrono::steady_clock::now(); | |
for (float &f : data) { | |
f *= 0.3333333333F; | |
} | |
const auto end = std::chrono::steady_clock::now(); | |
doNotOptimizeAway += std::accumulate(data.begin(), data.end(), 1, std::multiplies<float>()); | |
return std::chrono::duration_cast<std::chrono::microseconds>(end - start); | |
} | |
template <int nElements> std::chrono::microseconds benchmarkDivisionF32() { | |
srand(0); | |
std::array<float, nElements> data; | |
for (int i = 0; i < nElements; ++i) { | |
data[i] = rand(); | |
} | |
const auto start = std::chrono::steady_clock::now(); | |
for (float &f : data) { | |
f /= 3.0F; | |
} | |
const auto end = std::chrono::steady_clock::now(); | |
doNotOptimizeAway += std::accumulate(data.begin(), data.end(), 1, std::multiplies<float>()); | |
return std::chrono::duration_cast<std::chrono::microseconds>(end - start); | |
} | |
static auto getFastestRun = [](const int iterations, auto f) { | |
std::chrono::microseconds minDuration{999999}; | |
for (int i = 0; i < iterations; ++i) { | |
const std::chrono::microseconds duration = f(); | |
if (duration.count() < minDuration.count()) { | |
minDuration = duration; | |
} | |
} | |
std::cout << minDuration.count() << " µs\n"; | |
}; | |
auto main() -> int { | |
constexpr int nElements = 200000; | |
constexpr int nIterations = 5000; | |
getFastestRun(nIterations, []() { return benchmarkMultiplicationF32<nElements>(); }); | |
getFastestRun(nIterations, []() { return benchmarkDivisionF32<nElements>(); }); | |
std::cout << "\n"; | |
return doNotOptimizeAway; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment