ctimesleeptimeval

Can I pass a timeval as argument to sleep?


Can I pass a timeval struct as the argument for a sleep function? I want to do this since the timeval struct can get very precise, since you can control the microseconds and I would like to sleep for a certain amount of microseconds. Can I do this?


Solution

  • You could do something like:

    struct timeval {long tv_sec; long tv_usec;};
    
    struct timezone {int tz_minuteswest; int tz_dsttime; };    
    
       struct timeval tp;
       struct timezone tzp;
       int i;
    
       i = gettimeofday(&tp,&tzp);
    

    And using that you can implement a delay function. Please see this example.

    However if you want a precise delay you could use functions that enable you to get more precise delay such as nanosleep()

    struct timespec tim, tim2;
    tim.tv_sec = 1;
    tim.tv_nsec = 1000000000L; //1,000,000,000 nanoseconds = 1 second
    
    nanosleep(&tim , &tim2);
    /*code after 1 second sleep*/