timer to calculate seconds not being implemented properly - c++

I am making a timer to calculate the number of seconds until the user presses 3 however the program doesn't work, and no value is saved in the integer variable 'sec'.
where am i wrong?
I have include windows.h and ctime.h
Here's the code:
void func(){
int sec=0
cout<<"Press 3 to end Timer";
cin>>t;
while(t!=3){
Sleep(1);
sec++;}
if(t==3)
{
cout<<"Timer ended";
}
}

This is because cin >> t is blocking. That is, execution doesn't move to your while-loop until the input is complete.
Something like this would work:
#include <chrono>
// This is just to make the example cleaner.
using namespace chrono;
...
system_clock::time_point startTime = system_clock::now();
cin >> t;
system_clock::time_point endTime = system_clock::now();
milliseconds duration = time_point_cast<milliseconds>(endTime - startTime);
At this point, duration.count() is the number of milliseconds spent waiting for input. You can do some math to turn it into seconds, or you could use seconds instead like this:
seconds duration = time_point_cast<seconds>(endTime - startTime);
but in this case, 2.9 seconds will show up as 2 seconds (I think). So I'd do this to output it:
cout << "Duration: " << (double)duration.count() / 1000.0 << endl;
Or something along those lines. I'm typing this raw, so there might be typos.

Related

How to calculate time taken to execute C++ program excluding time taken to user input?

I'm using the below code to calculate the time for execution. It works well when I take input from ./a.out < input.txt. But when I manually write my input it also includes that time. Is there a way to exclude the time taken by the user to input?
auto begin = chrono::high_resolution_clock::now();
// my code here has cin for input
auto end = chrono::high_resolution_clock::now();
cout << chrono::duration_cast<chrono::duration<double>>(end - begin).count() << " seconds";
Edit: I know that we can count the time before cin and after then subtract it. Is there any other way?
A straightforward approach would be to "Freeze time" when user input is required, so instead of creating the end variable after the input lines, create it before the input lines and restart time calculation again after the input:
double total = 0;
auto begin = chrono::high_resolution_clock::now();
// code that needs time calculation
auto end = chrono::high_resolution_clock::now();
total += chrono::duration_cast<chrono::duration<double>>(end - begin).count();
// your code here that has cin for input
begin = chrono::high_resolution_clock::now();
// code that needs time calculation
end = chrono::high_resolution_clock::now();
total += chrono::duration_cast<chrono::duration<double>>(end - begin).count();
cout << total << " seconds";

can anyone explain the working of the following code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
more specifically can you please explain the working of following lines:
clock_t delay = secs * CLOCKS_PER_SEC;
clock_t start = clock() ;
while ( clock() - start < delay )
and the significance of semicolon in the next line.
#include<iostream>
#include<ctime>
int main () {
using namespace std;
cout << "Enter the delay time in sec: ";
float secs;
cin >> secs;
clock_t delay = secs * CLOCKS_PER_SEC;
cout << "starting \a\n" ;
clock_t start = clock() ;
while (clock() - start < delay )
;
cout << "dont \a\n" ;
return 0;
}
Overall, this program takes your delay in seconds, and prints output after waiting for the specified time.
Now lets break each statement:
clock_t delay = secs * CLOCKS_PER_SEC;
you can think this line as converting your input delay (which is in seconds), to the unit that c++ clock library uses (clock_t). Generally CLOCKS_PER_SEC is equal to 1,000,000.
clock_t start = clock() ;
This line returns the current processor time, in clock_t units.
while (clock() - start < delay ) ;
represent an empty while loop, to wait until the current time - start time (The time difference) becomes greater than delay.
An empty while loop can also be written as
while(condition) {}

Generate a Random number every 2 seconds? C++ Srand

I am studying C++ in order to make a game and I was able to generate a random number every second using the functions of srand. But I wanted the number to be different every 2 second instead.
Say t is the current time in seconds (time(0)). It is obvious that t changes once per second. Then t/2, because of rounding, changes every two seconds.
Here is a simple way to fix the code.
Put a clock() in an infinite while loop and let the clock count so that when it reaches two seconds, it triggers rand() to generate a new random number. Reset the clock(). Repeat infinitely.
Now the Math behind:
As you already know, delta time is the final time, minus the original time.
dt = t - t0
This delta time, though, is simply the amount of time that passes while in the while loop.
The derivative of a function represents an infinitesimal change in the function with respect to one of its variables. Our deltaTime.
The derivative of a function with respect to the variable is defined as http://mathworld.wolfram.com/Derivative.html
f(x + h) - f(x)
f'(x) = lim -----------------
h->0 h
First you get a time, i.e TimeZero = clock() , for reference.
Then you subtract that time from a new time you just got and devide it by h. h is CLOCKS_PER_SEC. Now delta time is
deltaTime = (clock() - TimeZero) / CLOCKS_PER_SEC;
And when deltaTime > secondsToDelay, you generate a new random number.
Putting all that into code results in this:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
cout << "Generate a new random number every 2 seconds \n\n";
// create a clock and start timer
clock_t TimeZero = clock(); //Start timer
double deltaTime = 0;
double secondsToDelay = 2;
bool exit = false;
// generate random seed using time
srand(time(0));
while(!exit) {
// get delta time in seconds
deltaTime = (clock() - TimeZero) / CLOCKS_PER_SEC;
cout << "\b" << secondsToDelay - deltaTime << "\b";
// compare if delta time is 2 or more seconds
if(deltaTime > secondsToDelay){
cout << " ";
// generate new random number
int i = rand() % 100 + 1;
cout << "\nNew random : " << i << " \n";
//reset the clock timers
deltaTime = clock();
TimeZero = clock();
}
}
return 0;
}

clock() function always returning 0 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
The C clock() function just returns a zero
I ran the following code to test the working of clock() function. I work on ubuntu 12.04.
#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks*10)/CLOCKS_PER_SEC;
return diffms;
}
int main()
{
string name;
int i;
clock_t begin=clock();
cout << "Hi what is your name? ";
getline(cin, name);
clock_t end=clock();
cout << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;
return 0;
}
But no matter how much time i take to write my name, the time elapsed is always shown as 0ms.
Can you tell me what is the problem?
clock() returns the number of ticks USED SINCE THE PROGRAM STARTED executing. There is no need (in this specific) example to get the clock_t begin value.
Try printing out both the begin and end values and see what they are. They're likely both 0 or close to 0 as waiting for user input doesn't use CPU time.
Either way, I recommend the time() function as you don't need tick precision.
http://www.cplusplus.com/reference/clibrary/ctime/time/
I think you should be using the time() function. Here is how it works: http://asust.in/007D
You just call it and it returns the number of seconds since Unix epoch (January 1, 1970).
The clock() function returns the number of clock ticks since the program started. Here: http://asust.in/007E

C++ clock() function giving incorrect values

I was trying to program a Timer class (unaware that boost had one), then when that wasn't working, I tried to just output the value of clock(), using this code:
#include <ctime>
#include <iostream>
int main()
{
for(int i = 0; i < 50; ++i)
{
std::cout << std::clock() << " ";
}
return 0;
}
When I run the program, I get a series of 0s. I have a similar experience when using boost thread sleep functions to spread out timing a little longer (although after a few seconds, it jumps from 0 to 10,000 and keeps outputting 10,000).
I'm running Gentoo Linux. Is this a platform thing? A C++ thing? What's going on?
Edit: Strangely the jump to 10000 comes after a number of seconds, not milliseconds. When I was sleeping my thread for a second at a time, it took five or six seconds to get to 10000. However, if I'm understanding correctly. The time the thread spends sleeping doesn't contribute towards the clock() count? (Which would make sense; why would it be executing clock cycles if it's sleeping?)
The clock() return value is specified in microseconds. But typical granularity of whatever low-level system call the clock() implementation uses is much lower. So it seems that on your system the granularity is 10ms. Also note that clock() does NOT measure real time - it measures CPU time used by the program. So the time flows when your program controls the CPU, and it freezes when your program is suspended - sleeping, for example.
std::clock's resolution is unspecified. In most cases, it's resolution is going to be about 10ms. Hence the jump.
Try the following:
#include <ctime>
#include <iostream>
int main()
{
for(int i = 0; i < 50; ++i)
{
for (int j = 0; j < 500; ++j )
{
std::cout << j << " ";
}
std::cout << std::endl;
std::cout << std::clock() << std::endl;
}
std::cout << std::endl;
return 0;
}
On my system, I see the return value of clock() staying at 0 until at some point it jumps to 10000. It stays at 10000 till the end. If I remove the std::cout in the inner loop, the return value of clock() stays at 0 all the way through. Looks like clock() returns values in increments of 10000 only.
If I change the inner loop to compute the square root of j and print the return value of sqrt(), the return value of clock() goes up to 50000, but is still increases in increments of 10000.
on my 64 bit operating system the CLOCKS_PER_SEC speed is 1000.and the values of clock comes in milliseconds. perfect timing will be extracted from the code below.
int main(){
clock_t a,b;
int c,d,e,f;
c=clock();
scanf("%d",&e);
d=clock();
f=(d-c)/CLOCKS_PER_SECOND;
printf("timing is %d seconds",f);/*for 64 bit operating system
CLOCKS_PER_SECOND is 1000*/
}