Skip to content

Instantly share code, notes, and snippets.

@htfy96
Last active April 4, 2016 15:04
Show Gist options
  • Save htfy96/d36c6c388c0c901bc31ca95cc772db1d to your computer and use it in GitHub Desktop.
Save htfy96/d36c6c388c0c901bc31ca95cc772db1d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cstddef>
#include <cstdint>
#include <type_traits>
using namespace std; //for convinience
struct Fixed
{
static const float up ;
static const float down ; // avoid float-point division
uint32_t d;
explicit Fixed(float x):
d(x * (1 << 16))
{}
explicit Fixed(const uint32_t x, std::false_type) : d(x) {} //internal use only
float getFloat()
{
return static_cast<float>(d) * down;
}
Fixed operator*(const Fixed other)
{
return Fixed((uint32_t)(((uint64_t)d * other.d) >> 16), std::false_type());
}
};
const float Fixed::up = 1 << 16;
const float Fixed::down = 1 / Fixed::up;
int main()
{
// tested on gcc 5.3.0 -O2 enabled
// 0.88s
//Fixed a(2.5), b(2.5);
//for (int i=0; i<1000000000; ++i)
//{
//a = a * b;
//}
//cout << a.getFloat() << endl;
// 1.47s
float a(2.5), b(2.5);
for (int i=0; i<1000000000; ++i)
{
a = a * b;
}
cout << a << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment