Creating a simple timer
Jul 28, 2012 at 1:21am UTC
How could I make this function delay the progress of my program? I would rather learn how to make a timer like this and not just use a simple one word function from a library.
Thanks,
Nick
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
void delayProgram(double secondsToDelay)
{
clock_t startTime = clock(); //Start timer
clock_t testTime;
clock_t timePassed;
double secondsPassed;
while (true )
{
testTime = clock();
timePassed = startTime - testTime;
secondsPassed = timePassed / (double )CLOCKS_PER_SEC;
if (secondsPassed >= secondsToDelay)
{
cout << secondsToDelay << "seconds have passed" << endl;
break ;
}
}
}
Jul 28, 2012 at 1:52am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <ctime>
#include <cstdlib>
int main(int args,char * argv[])
{
clock_t startTime = clock(); //Start timer
double secondsPassed;
double secondsToDelay = atof(argv[1]);
std::cout << "Time to delay: " << secondsToDelay << std::endl;
bool flag = true ;
while (flag)
{
secondsPassed = (clock() - startTime) / CLOCKS_PER_SEC;
if (secondsPassed >= secondsToDelay)
{
std::cout << secondsPassed << " seconds have passed" << std::endl;
flag = false ;
}
}
}
1 2 3 4
$ g++ timer.cpp -o timer.out
$ ./timer.out 5
Time to delay: 5
5 seconds have passed
Actually, no comments needed I think.
Jul 28, 2012 at 2:44am UTC
Thank you!
Topic archived. No new replies allowed.