So, our class was given this code to compile and run, and see how long it takes to run for different sized inputs N:
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[]) {
int N;
sscanf(argv[1], "%d", &N);
vector<double> data(N);
for(unsigned int i=0; i<N; i++) {
data[i] = rand()/(RAND_MAX+1.0);
}
sort(data.begin(), data.end());
copy(data.begin(), data.end(), ostream_iterator<double>(cout,"\n"));
}
We have never been taught C++ and are not expected to know anything about how this code works. They even give us the commands for compiling and running the code. However, they failed to mention how exactly we can measure how long the program takes. I have tried with this approach:
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <time.h>
using namespace std;
int main(int argc, char *argv[]) {
double start_time = time(NULL);
int N;
sscanf(argv[1], "%d", &N);
vector<double> data(N);
for(unsigned int i=0; i<N; i++) {
data[i] = rand()/(RAND_MAX+1.0);
}
sort(data.begin(), data.end());
copy(data.begin(), data.end(), ostream_iterator<double>(cout,"\n"));
double end_time = time(NULL);
printf("%lf seconds\n", end_time - start_time);
}
Literally just including a time library, then getting the current time before and after the program runs, and printing the difference at the end.
All of which I copied straight from this site actually because, again, none of us know (or apparently need to know) how to code anything in C++ until next year.
However, the output is always
0.000000 seconds
even for inputs of sizes in the millions or billions, where I can see that it takes a few seconds or minutes to process.
What am I doing wrong in this code?
I've read some sources saying to use the Chrono library to measure time but I was getting far more complicated errors when I tried that. This at least compiles and runs, but is just wrong every time.