-
<time.h> in program
I am trying to find out how much time it takes to complete an execution of a program in Linux, by executing it from a new process. I am using the <time.h> time() function, but I get strange numbers pushed into the clockTimeA vector, but can't figure out why. Any suggestions as to what the problem may be? Thanks.
Here is my code:
Code:
#include <ctime>
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int main()
{
pid_t pid;
time_t start, finish; //time variables
vector <double> clockTimeA;
double sdA;
double meanA = 0;
double varianceA = 0;
ofstream OUTPUTFILE;
OUTPUTFILE.open("Runtime_Data_Fork_Linux_A.txt");
pid = fork();
for(int i = 0; i <= 1; i++)
{
if(pid == 0)
{
start = time(NULL);
//Process A
///////////////////////////////////////////////
execlp("/A", "A", NULL);
}// end if loop
if (pid > 0)
{
wait();
cout <<"waiting for child process to finish" << "\n";
//get finish time for process A
finish = time(NULL);
cout << "A started at: " << " " << start << " " << "and finished at: " << finish << " " << "\n";
clockTimeA.push_back((double) (finish-start) ) ;
cout << "1st time is: " << clockTimeA[0] << "\n" ;
}
} // end 30 times loop
if(pid > 0)
{
for(int i = 0; i < clockTimeA.size(); i++)
{
OUTPUTFILE << ((double) (finish-start)) << "\n";
meanA += clockTimeA[i]/2;
}
OUTPUTFILE << "\n" << "Mean" << "\n" << meanA << "\n" << "\n";
for(int i = 0; i < clockTimeA.size(); i++)
{
varianceA += (pow((clockTimeA[i] - meanA), 2))/2 ;
}
sdA = sqrt(varianceA);
OUTPUTFILE << "StdDev" << "\n" << sdA << endl;
}
return 0;
}
-
start is only updated in the child process, it remains uninitialised in the parent process.
Remember, immediately after the fork(), you have TWO copies of the program running. Changing variables in one of them does not affect the other.
-
Why not just use
time your_program
?
Valery
-
If u really need this kind of thing, you can create pipe(write/read values from that pipe) and use that for proper values, but that will involved extra overhead.
Regards,
Amit Sahrawat