I am preparing for a coding challenge, where the fastest calculation of pi to the 10000th digit wins. all calculations will be run on a raspberry Pi4 running linux during competition. I want to know which code runs the fastest, so I can know which function to submit.
so I wrote a little program named "lol" to try and establish a baseline around a known time.
//lol....lol is an exe which calls usleep()
#include <unistd.h>
using namespace std;
int main(){
usleep(100);
return 0;
}
then to measure execution time, I wrote this:
#include <chrono>
#include <stdlib.h>
#include <iostream>
using namespace std::chrono;
using namespace std;
int main(int argc, char **argv){
//returns runtime in nanoseconds
//useage: runtime <program>
//caveates: I put the exe in /home/$USER/bin
//start timing
auto start = high_resolution_clock::now();
//executable being timed:
system(argv[1]);
// After function call
auto stop = high_resolution_clock::now();
auto duration = duration_cast<nanoseconds>(stop - start);
cout << argv[1] << " " << duration.count() << endl;
return 0;
}
my issue is that the run time seems to be wildly variant. Is this because I'm running in userspace and my system is also doing other things? why am I not getting more consistent run times?
$ ./run_time lol
lol 13497886
$ ./run_time lol
lol 11175649
$ ./run_time lol
lol 3340143
./run_time lol
lol 3364727
$ ./run_time lol
lol 3372376
$ ./run_time lol
lol 1981566
$ ./run_time lol
lol 3385961
CodePudding user response:
- instead of executing a program, measure a function completion in a single program:
auto start = high_resolution_clock::now();
//function being timed:
my_func();
// After function call
auto stop = high_resolution_clock::now();
you are using chrono
header. so why usleep
when you can use sleep_for
:
https://en.cppreference.com/w/cpp/thread/sleep_for
The merits of this contest is not how you micro-optimize to save 1ns
. It`s about choosing the right algorithm to calculate pi.