user1391863
user1391863

Reputation: 137

how to measure time in linux?

I want to write data into a file when given time parameter : for example I get x= 7 -> meaning for the next 7 seconds write some random data into a file I got some difficulties doing that , I've tried using : clock() and struct timeval but it didn't work

things I've tried:

struct timeval start, end;
gettimeofday(&start, 0);
while(  gettimeofday(&end, 0) && end.tv_sec - start.tv_sec < sec )
  {
    write....
  }

but it stops the clock..

would love to get some help. thanks

Upvotes: 2

Views: 668

Answers (3)

Tuxdude
Tuxdude

Reputation: 49473

You should consider using clock_gettime instead of gettimeofday which is claimed to be obselete by POSIX.1-2008.

#include <time.h>

int main()
{
    struct timespec start, end;
    int sec = 10; // Number of seconds

    clock_gettime(CLOCK_REALTIME, &start);
    while( !clock_gettime(CLOCK_REALTIME, &end)
           && end.tv_sec - start.tv_sec < sec )
    {
        // Write ...
    }
}

NOTE: If you're using gcc or g++ to compile your program, you need to link against the librt library by appending -lrt:

gcc myprogram.c -o myprogram -lrt

Upvotes: 0

gcbenison
gcbenison

Reputation: 11963

Consider order of operations... Try adding parens around the operands of &&

man: gettimeofday()

RETURN VALUE
    The `gettimeofday()` function shall return 0 and 
    no value shall be reserved to indicate an error.

In you code because gettimeofday() returns 0 on success while loops break.

Below you code rectified with ! logical Not operator.

while(  (!gettimeofday(&end, 0)) && end.tv_sec - start.tv_sec < sec )
  {
    write....
  }

Upvotes: 1

MByD
MByD

Reputation: 137272

If getTimeOfDay succeeds, it returns 0, and then your while condition fails. Try:

while(  (gettimeofday(&end, 0) == 0) && end.tv_sec - start.tv_sec < sec )
{
    write....
}

Upvotes: 7

Related Questions