### array of timespec handling

Hi
I have a code that call a function then measure the average runtime
int main()
{
int numOfRun =5;
timespec timeArray[numOfRun];
for(int h=0; h<numOfRun ;h++)
run('A',h,numOfRun ,timeArray);
// calculate average runtime
long sumRunningTime =0;
for( int i=0; i<numOfRun ; i++)
sumRunningTime = sumRunningTime +(timeArray[i].tv_nsec)*1e-6;

long averageRunTime = sumRunningTime /(long)numOfRun ;

excel_file<< averageRunTime ;
}

void run(char c,int iteration,int numOfRun , timespec timeArray[])
{
timespec time1 ;
// time1 is measured based on some calculations in this function and stored correctly in my excel sheet
excel_file<< (time1.tv_nsec)*1e-6;
// then I store it in the array, in each of the five executions
timeArray[iteration]= time1;

}// end function run

My problem is:
averageRunTime is zero in the excel sheet !
Last edited on
sumRunningTime is a long, which is an integer type.
You are trying to add a value of type double to it: (timeArray[i].tv_nsec)*1e-6
This value is being multiplied by a very small amount (1e-6), and the result will be truncated to an integer value when you add it to sumRunningTime.

After this loop, when you calculate sumRunningTime /(long)numOfRun, you are doing integer division, which also truncates the decimal part off of the division. So if sumRunningTime is less than numOfRun, the final result will be truncated to 0.

In other words, you want to change sumRunningTime to type `double`.

PS: Your question would be more appropriate for the Beginners or General C++ sections of the forum, as your question is not specific to Linux/Unix.

PPS: main should be int main() not void main(), because The Standard Says So™.
Last edited on
Many thanks.

double sumRunningTime =0;
for( int i=0; i<numOfRun ; i++)
sumRunningTime = sumRunningTime +(timeArray[i].tv_nsec)*1e-6;

double averageRunTime = sumRunningTime / numOfRun ;

Is it better to use double or long double for sumRunningTime and averageRunTime ?
 Is it better to use double or long double

Just use double. Depending on the platform, there might not even be a difference between long double and double. Especially for something like the runtime of a movie, such precision is just a waste of space/computation for no real gain.
Topic archived. No new replies allowed.