bhjghjh bhjghjh - 1 year ago 68
Bash Question

calculating program's runtime for each iteration using Unix program time

I wish to calculate runtime of my program which approximates PI using Monte Carlo Method. I have written a unix shell script which feeds the program No of points, N = 10^{k} , for K = 1,2, ...7.
Now I wish to find the execution time for Each N in Unix program time. My unix shell script looks as follows:


while [[ k -le 7 ]]
echo "$k N" | ./pi $N

((k = k + 1))
((N = N * 10))

Now when I type:
$ time ./
, it returns me the total execution time

10 3.6 0.1459155902616465
100 3.08 0.01960555055392467
1000 3.104 0.01196611328551369
10000 3.1284 0.004199352062629202
100000 3.1432 0.0005116342528909465
1000000 3.139704 0.0006011771092076384
10000000 3.141432 5.113762588206346e-05

real 0m0.583s
user 0m0.560s
sys 0m0.012s

I was wondering if I have to write a bash script to get execution time for Each N input or I have to do something in my code. I am also sharing the code I used to generate data:

Program to compute Pi using Monte Carlo methods,
takes bash input from shell to feed No of points
compile using:
$ g++ -o pi monte_pi.cpp
$ chmod 755
$ ./

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

using namespace std;

int main(int argc, char **argv)

double x,y,z,approx_PI, rel_err;
double a, b;
int i, NpointsInside=0;
const double pi = 3.14159265358979323846;

// set right and left edge of the circumscribing square
a = -1.0;
b = 1.0;

// convert command-line input to N = number of points
int N = atoi( argv[1] );

// initial seed value (use system time)

for(i=1; i<=N; i++)
// generate random numbers between left and right edges
x = a + static_cast <double> (rand()) /( static_cast <double> (RAND_MAX/(b-a)));
y = a + static_cast <double> (rand()) /( static_cast <double> (RAND_MAX/(b-a)));
z = x*x + y*y;
//check if there is absolutely no points inside circle
if (NpointsInside==0)
printf("No points inside circle, Increase npoints\n");

approx_PI = 4*double(NpointsInside)/double(N);

//estimate relative error
rel_err = fabs(pi-approx_PI)/fabs(pi);

cout << setw(10) << N << setw(20) << approx_PI << setw(30) << rel_err <<endl;

return 0;

Answer Source

By writing $ time ./ you are measuring time needed to execute, which has a loop in it. So you measure total time for all iterations. If you want to measure every iteration independently, you have to put time in invocation of the iteration:

echo "$k N" | time ./pi $N
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download