Skip to content

Instantly share code, notes, and snippets.

@gubatron
Last active November 8, 2018 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gubatron/612118b529bc7428325bb17bb5f4acef to your computer and use it in GitHub Desktop.
Save gubatron/612118b529bc7428325bb17bb5f4acef to your computer and use it in GitHub Desktop.
parity_benchmark.cpp
// g++ -std=c++11 parity_benchmark.cpp -o parity_benchmark
#include <iostream>
#include <chrono>
#include <functional>
std::int64_t now() {
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_\
epoch()).count();
}
bool isEven1(int n) {
return n % 2 == 0;
}
bool isEven2(int n) {
return n & 1 == 0;
}
void testFunction(int iterations, std::function<bool(int)> f, std::string testName) {
std::int64_t a = now();
for (int i=0; i < iterations; i++)
f(i);
std::int64_t duration = now() - a;
std::cout << testName << ": " << iterations << " iterations in " << duration << "ms." << std::endl;
}
int main() {
for (int i=0; i < 10; i++) {
std::cout << "Running test " << (i+1) << "..." << std::endl;
testFunction(99999999, isEven1, "modulus parity test");
testFunction(99999999, isEven2, "bit parity test");
std::cout << std::endl;
}
return 0;
}
@gubatron
Copy link
Author

gubatron commented Nov 8, 2018

Output

Running test 1...
modulus parity test: 99999999 iterations in 1856ms.
bit parity test: 99999999 iterations in 1794ms.

Running test 2...
modulus parity test: 99999999 iterations in 1838ms.
bit parity test: 99999999 iterations in 1800ms.

Running test 3...
modulus parity test: 99999999 iterations in 1836ms.
bit parity test: 99999999 iterations in 1795ms.

Running test 4...
modulus parity test: 99999999 iterations in 1836ms.
bit parity test: 99999999 iterations in 1793ms.

Running test 5...
modulus parity test: 99999999 iterations in 1840ms.
bit parity test: 99999999 iterations in 1793ms.

Running test 6...
modulus parity test: 99999999 iterations in 1842ms.
bit parity test: 99999999 iterations in 1795ms.

Running test 7...
modulus parity test: 99999999 iterations in 1840ms.
bit parity test: 99999999 iterations in 1802ms.

Running test 8...
modulus parity test: 99999999 iterations in 1869ms.
bit parity test: 99999999 iterations in 1796ms.

Running test 9...
modulus parity test: 99999999 iterations in 1843ms.
bit parity test: 99999999 iterations in 1796ms.

Running test 10...
modulus parity test: 99999999 iterations in 1864ms.
bit parity test: 99999999 iterations in 1798ms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment