0

I'm attempting to time a function using the gettimeofday() function. I'm able to acquire the time in microseconds, but when attempting to divide it by a long to get time in seconds my value is truncated to a single integer. Does anyone have any insights as to why this is happening? I had assumed that division by a long = 1000000.0 would prevent this kind of truncation.

Timing of function:

struct timeval t1,t2;

gettimeofday(&t1, NULL);

// Computes C - C1 - using single thread
for (i=0; i < n; i++)
    for (j=0; j < p; j++)
    {
        C1[i][j]=0;
        for (k=0; k < m; k++)
            C1[i][j] += A[i][k]*B[k][j];
    }

gettimeofday(&t2, NULL);

Division applied here:

long divider = 1000000.0;
long elapsed = ((t2.tv_sec - t1.tv_sec) * 1000000.0L) + (t2.tv_usec - t1.tv_usec);
elapsed = (elapsed/divider);

printf("Time in seconds: %ld seconds\n", elapsed);

Any help is appreciated.

Alfabravo
  • 7,493
  • 6
  • 46
  • 82
Matt Koz
  • 67
  • 3
  • 10

2 Answers2

3

Long is an integer type meaning it won't hold decimals, you probably want to use double for divider and elapsed. More information on cplusplus.com

Note that you'll also need %lf to printf the value.

Correction: just %f as printf-format is apparently enough

Community
  • 1
  • 1
Kninnug
  • 7,992
  • 1
  • 30
  • 42
2

The long type is an integer type.

The problem is that you're trying to store a result which you want to be a float (or a double) in a long.

There are two problems here: 1- Your operands are never cast into float/double (implicit cast by the compiler), so all the intermediate operation returns an int or a long. 2- Your result is a long: even if your operands are float/double, your result will be cast to long.

What you have to do: use double variables.

double divider = 1000000.0;
double elapsed = ((t2.tv_sec - t1.tv_sec) * 1000000.0) + (t2.tv_usec - t1.tv_usec);
elapsed = (elapsed/divider);

printf("Time in seconds: %5.5f seconds\n", elapsed);
Arno
  • 745
  • 4
  • 17