I want to make a call - either a function call or doing some condition for a PERIOD of time ... typically 10 - 20 seconds.
I would get some user input for the amount of time and do that ...
What is the proper function to use on Linux/Unix systems?
gettimeofday seems to be the way to go ... or perhaps time_t time(time_t *t) ... seems simple. What is preferred?
So is it something like this you want? This will repeatedly call myfunc() for the next 20 seconds. So could do 1 call (if myfunc takes at least 20 seconds to run) or hundreds of calls (of myfunc() takes a few milliseconds to complete):
#include <time.h>
void myfunc()
{
/* do something */
}
int main()
{
time_t start = time(NULL);
time_t now = time(NULL);
while ((now - start) <= 20) {
myfunc();
now = time(NULL);
}
}
It's probably worth asking what you're ultimately trying to achieve. If this is for profiling (e.g., what's the average amount of time function f takes to execute), then you might want to look at other solutions - e.g., using the built-in profiling that gcc gives you (when building code with the "-pg" option), and analyzing with gprof.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With