Last active
January 7, 2020 17:48
-
-
Save kghose/ccecb4e886e2f6b26b0bad48371980b5 to your computer and use it in GitHub Desktop.
Testing with units in C++
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
#include <iostream> | |
#include <vector> | |
#include "units.h" | |
using namespace units::literals; | |
using namespace units; | |
typedef units::length::meter_t Meters; | |
typedef units::length::foot_t Feet; | |
Meters foo(Meters m) { return m + Meters{2}; } | |
int main(int argc, char *argv[]) | |
{ | |
std::vector<Feet> feet; | |
for (size_t i = 0; i < (1 << 23); i++) | |
{ | |
feet.push_back(Feet{static_cast<double>(i)}); | |
} | |
Meters sum = 0_m; | |
for (size_t i = 0; i < feet.size(); i++) | |
{ | |
sum += foo(feet[i]); | |
} | |
std::cout << sum; | |
} |
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
#include <iostream> | |
#include <vector> | |
typedef double Meters; | |
typedef double Feet; | |
Meters foo(Meters m) { return m + Meters{2}; } | |
int main(int argc, char *argv[]) | |
{ | |
std::vector<Feet> feet; | |
for (size_t i = 0; i < (1 << 23); i++) | |
{ | |
feet.push_back(Feet{static_cast<double>(i)}); | |
} | |
Meters sum = 0; | |
for (size_t i = 0; i < feet.size(); i++) | |
{ | |
sum += foo(feet[i] * 0.3048); | |
} | |
std::cout << sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
units.h
file is found here: https://github.com/nholthaus/units/blob/master/include/units.hCompiling with
clang++ --std=c++17 -o3
and profiling with Instruments on macOS results in 987ms run time for the strongly typed code and 429ms for the weakly typed code.