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) {}
Related
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";
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.
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;
}
I have started creating a c++ program to simulate job scheduling algorithms like FiFo and others. I am far from done but my main problem now is how to create the flow of time in my program.
This is my main code so far:
for (i = 1; i < 10; i++)
{
Time1 = clock();
//this is the alogrithm to generate poisson arrival sequence
do{
k = k + 1;
// Generate a random number between 0 and 1
// return a uniform number in [0,1].
double u = rand() / (double)RAND_MAX;
p = p * u;
}while (p > L);
A[i] = k-1;
Time2 = clock();
DT = Time2 -Time1;
TotalTime=TotalTime + DT;
cout << " Total time " << TotalTime
<< " table :" << A[i]
<< " Arrival Time "
<< TotalTime <<endl ;
My main problem is :
my time measuring units with clock are that the time units that are outputted from clock() function are "weird" numbers. Should I use another function?
Results from 10 iteration
Total time 6.19522e+032 table :28 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :29 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :30 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :31 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :32 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :33 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :34 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :35 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :36 Arrival Time 6.19522e+032
PS: I can provide the rest of the code if you want to run it in your machine.
Job scheduling would be much, much easier to do as a "discrete-event" simulation. Check out this tutorial paper to see how such models can be constructed. The framework in the paper is in Java (and has also been implemented in Ruby), but would be straight-up to port to C++.
So the first point is that clock() returns a clock_t variable so, although I don't think it will really make much of a different, make Time1 and Time2 be of type clock_t. As for the main question and from the comments, looks like you just forgot to initialize TotalTime to zero, which would explain the huge numbers.
If the output is all zero then yes the loop probably is running very quickly but you can also increase the number of decimal places you output by using setprecision. Run the following code to see the difference, cout.setprecision(int value) will determine how many decimal places to show.
#include <iostream>
int main() {
double d = 1.0/3.0;
std::cout.precision(15);
std::cout << d << std::endl;
std::cout.precision(3);
std::cout << d;
return 0;
}
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