-
C Programming Timing
I am a begineer to C Programming.
Is there a command to give processor independent accurate timing.
Let me explain.
I want to write the following program:
1) Print x to the screen
2) Wait for 5secs
3) Print x to the screen
4) Jump to 1)
I want the program to wait 5secs between printing "x" no matter what PC processor I use.
Hence, I can not have:
1 Printf("x");
2 If (x=0;x<200000;x++);
3 Go to 1
I must have something like:
1 Printf("x");
2) Get time now;
3) Let timstart=Get time now
4) Let timstart=Get time now + 5seconds
4) Get Time
5) IF GET Time < timstart go to 4 else go to 1
Thanks for you help
-
There are individual API that can sleep for "around" n milliseconds.
However, most Operating Systems are not real time and can therefore not wait for exactly the amount you specify.
You might stat by telling the OS, I think, or give a search for sleep a go.
-
C has a time and date library that lets you do stuff like that.
Code:
#include <stdio.h>
#include <time.h>
void waitFor( double seconds )
{
time_t start = time( NULL );
double diff = 0;
do
{
diff = difftime( time( NULL ), start );
}
while ( diff < seconds );
}
int main( void )
{
puts( "x" );
waitFor( 5.0 );
puts( "x" );
return 0;
}
-
No!
This will consume 100% CPU while waiting!
Use appropriate Sleep functions. They use no CPU while waiting.
-
sleep() on *nix systems. Sleep() on Windows systems. Note the case of the first letter. Also, beware what arguments to give it since they accept different arguments.
-
Some operating systems can do this, at the expense of everything else in the system. And not just the humans using it, but all the devices wanting to interrupt the system too.
-
Thank You
Thank you for all you replies especially.