Skip to content

Instantly share code, notes, and snippets.

@kghose
Last active January 7, 2020 17:48
Show Gist options
  • Save kghose/ccecb4e886e2f6b26b0bad48371980b5 to your computer and use it in GitHub Desktop.
Save kghose/ccecb4e886e2f6b26b0bad48371980b5 to your computer and use it in GitHub Desktop.
Testing with units in C++
#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;
}
#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;
}
@kghose
Copy link
Author

kghose commented Jan 7, 2020

The units.h file is found here: https://github.com/nholthaus/units/blob/master/include/units.h

Compiling 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.

Screen Shot 2020-01-07 at 12 47 05 PM
Screen Shot 2020-01-07 at 12 46 54 PM

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