Some time has passed since I did something similar, but something like this will work:
#include <time.h> time_t t2, t1 = time(NULL); while(CONDITIONS) { time_t t2 = time(NULL); if(difftime(t2, t1) > timeModifier) { //DO the stuff! t1 = time(NULL); } }
I should note, however, that I am not familiar with the accuracy of this method, I think it measures the difference in seconds.
If you need something more precise, use the clock()
function, which has a number of milliseconds from 12:00 AM from January 1, 1980 to the next 10 milliseconds. Maybe something like this:
#include <time.h> clock_t t2, t1 = clock(); while(CONDITIONS) { t2 = clock(); if((t2-t1) > someTimeElapsed*timeModifier) { //DO the stuff! t1 = clock()); } }
Update: You can even cast the processor to other threads and processes by adding this after the if
ends:
else { usleep(10000); //sleep for ten milliseconds (chosen because of precision on clock()) }
source share