Calculating π for no good reason
So the other day I had some time to kill and was thinking that I might be fun to repeat some of the exercises I did when I was studying high performance computing in the data center of RWTH-Aachen University of Technology.
After all that years I actually had to lookup that formula for π that was used all the time to burn some cpu cycles. Still knowing some things about C++ and adding some C++11 functions, I could come up with this program.
#include <iostream> #include <chrono> int main() { auto before = std::chrono::system_clock::now(); auto beforeMilliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(before.time_since_epoch()).count(); int nmax=1000000000; int i=3; double pi=4.0; bool sign=true; while (i<=nmax) { if (sign) { pi-=4.0/i; } else { pi+=4.0/i; } sign=!sign; i+=2.0; } std::cout << "PI=" << pi << std::endl; auto after = std::chrono::system_clock::now(); auto afterMilliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(after.time_since_epoch()).count(); int nflops = nmax; // nmax/2 iterations with 2 flops per iteration double seconds = (afterMilliseconds - beforeMilliseconds)/1000.0; int flops = nflops / seconds; std::cout << "MFLOPS=" << flops/1000000.0 << std::endl; return 0; }
Of course, this code needs to be compiled. So I saw need for a Makefile:
DEBUG:=
OPT:=
CPPFLAGS:=$(DEBUG) $(OPT)
app.exe: app.cpp
g++ $(CPPFLAGS) -o app.exe app.cpp
My program is having a look on the stopclock to see how long the main loop is running. Knowing that each loop iteration consists of two floating point operations, I can then calculate the number of floating point operations per second – an important metric when looking at high performance code. In my case I wanted to compare the performance of an un-optimized binary (app.exe) against that of an optimized binary (app-O3.exe) and it turned out that the optimized binary is with a factor of 2.3 more performanat than the un-optimized version. Nice!
matthias@localhost$ ./app.exe
PI=3.14159
MFLOPS=411.353
matthias@localhost$ ./app-O3.exe
PI=3.14159
MFLOPS=949.668
Kommentar abschicken