Created
August 10, 2017 03:56
-
-
Save Biendeo/4168a3779901dcbaac596d13e05d0091 to your computer and use it in GitHub Desktop.
Carmack Fast Inverse Square Root
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 <cmath> | |
#include <iomanip> | |
#include <atomic> | |
#include <mutex> | |
#include <thread> | |
#include <condition_variable> | |
#include <sstream> | |
#include <vector> | |
#include <fstream> | |
static int threadCount = 0; | |
std::mutex m; | |
float Q_rsqrt(float number) { | |
long i; | |
float x2, y; | |
const float threehalfs = 1.5F; | |
x2 = number * 0.5F; | |
y = number; | |
i = *(long *)&y; // evil floating point bit level hacking | |
i = 0x5f3759df - (i >> 1); // what the fuck? | |
y = *(float *)&i; | |
y = y * (threehalfs - (x2 * y * y)); // 1st iteration | |
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed | |
return y; | |
} | |
void loopThread(unsigned long low, unsigned long high) { | |
unsigned long i = low; | |
std::stringstream s; | |
s << "csv/" << low << "-" << high << ".csv"; | |
std::ofstream file; | |
file.open(s.str()); | |
do { | |
float* f = (float*)&i; | |
file << std::hex << i << "," << *f << "," << (1.0f / sqrtf(*f)) << "," << Q_rsqrt(*f) << "\n"; | |
++i; | |
} while (i != high); | |
m.lock(); | |
--threadCount; | |
m.unlock(); | |
file.close(); | |
} | |
int main() { | |
std::vector<std::thread> threads; | |
unsigned long i = 0; | |
unsigned long amount = 256 * 256; | |
do { | |
threads.emplace_back(std::thread(loopThread, i, i + amount - 1)); | |
std::cout << "Starting: " << i << "-" << i + amount - 1 << "\n"; | |
m.lock(); | |
++threadCount; | |
m.unlock(); | |
// I have no idea what I'm doing. | |
while (threadCount >= std::thread::hardware_concurrency()) {} | |
i += amount; | |
} while (i != 0); | |
for (auto& t : threads) { | |
t.join(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment