C++ Clock Not Working [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I wanted to make a simple program where the user has to enter a prompted number(1-4). Where the conditions of continuing is based on entering the number in the amount of time as defined by which level the user has selected and, of course, entering the correct number. The problem is that the program recognizes if the number is correct, however you can take as long as you like and it won't stop the game. This "15 minute" program was supposed to be a delve back into C++, however it has turned into a weekend long project of confusing clock algorithms and confusion. Below is the entire source code. Any help would be great...
EDIT: Here is a link to an online C++ emulator so you can test out the program in it's current state...
#include <iostream>
#include <time.h>
#include <ctime>
#include <unistd.h>
using namespace std;
int main() {
//input
string numberGuessed;
int intNumberGuessed;
int score = 0;
int actualNumber;
int gameOver = 0;
//Level Select Variables
char level = {0};
string input = " ";
double timeForInput;
//initialize random seed
srand (time(NULL));
//Generates random number
actualNumber = rand() % 4 + 1;
//LEVEL SELECTOUR
cout << "Select A Level: 'e' 'm', or 'h': ";
getline(cin, input);
if (input.length() == 1) {
level = input[0];
}
if (level == 'e') {
cout << "You Have Selected Easy..." << endl;
cout<< "You Have .5 Second to Enter" << endl;
timeForInput = 5;
} else if(level == 'm'){
cout << "You Have Selected Medium..." << endl;
cout<< "You Have .2 Seconds to Enter" << endl;
timeForInput = 2;
} else if(level == 'h'){
cout << "You Have Selected HARD!!!" << endl;
cout<< "You ONLY Have .1 Seconds to Enter" << endl;
timeForInput = 1;
} else {
cout << "You LOSE! GOOD DAY SIR!" << endl;
}
//Instructions and Countdown
cout<<"Press The Number and Hit Enter in The Amount of Time Provided"<<endl;
sleep(1);
cout<<"3"<<endl;
sleep(1);
cout<<"2"<<endl;
sleep(1);
cout<<"1"<<endl;
sleep(1);
cout<<"GO!"<<endl;
cout<<"--------------------------------------------------------------------------------"<<endl;
cout<< "Enter the Numbers As They Appear:"<<endl;
cout<<endl;
cout<<endl;
cout<<endl;
sleep(1);
double duration = 0.0;
do {
//Procedere For Each Round
clock_t start;
clock_t finish;
start = clock();
finish = clock();
double delay = (double)(finish-start);
//Clock
start = clock();
cout<<"The number is: "<< actualNumber<<endl;
getline(cin, numberGuessed);
intNumberGuessed = stoi(numberGuessed);
finish = clock();
double elapsed = (double)(finish-start);
elapsed-=delay;
duration = elapsed/CLOCKS_PER_SEC;
cout<<duration<<endl;
//Test User's input
if((intNumberGuessed == actualNumber) && (duration <= (timeForInput/10))){
score += 1;
gameOver = 0;
} else if ((intNumberGuessed != actualNumber) || (duration >= (timeForInput/10))) {
gameOver = 1;
}
//Reset Number
actualNumber = rand() % 4 + 1;
} while (gameOver != 1);
cout<<"You Failed!"<<endl;
sleep(1);
cout<<"Your Score Was: "<<score<<endl;
return 0;
}

In the standard, clock() is specified to return the approximate processor time used by the process. In particular that means that the duration resulting from an expression (finish-start) doesn't necessarily equal the amount of wall-clock time that has passed. For example if you measure four threads chewing up CPU for 1 second then you should get a result of about 4 seconds.
The way this is relevant to your program is that a program that is just waiting for input or sleeping is not using any processor time, so the result of (finish-start) will be zero.
#include <iostream>
#include <chrono> // std::chrono::seconds, milliseconds
#include <thread> // std::this_thread::sleep_for
#include <ctime> // std::clock()
int main() {
auto start_processor_usage = std::clock();
auto start_wall_clock = std::chrono::steady_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1));
auto finish_processor_usage = std::clock();
auto finish_wall_clock = std::chrono::steady_clock::now();
std::cout << "CPU usage: " << (finish_processor_usage - start_processor_usage) / CLOCKS_PER_SEC << '\n';
std::cout << "Wall clock: " << (finish_wall_clock - start_wall_clock) / std::chrono::milliseconds(1) << '\n';
}
The above program should output something like:
CPU usage: 0
Wall clock: 1000
Note that while *nix platforms in general correctly implement clock() to return processor usage, Windows does not. On Windows clock() returns wall-clock time. You need to keep this in mind when switching between Windows and other platforms.
Ok Sure. What is the syntax for a random int using <random>? – Noguiguy
#include <random>
int main() {
// initialize with random seed
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 engine(seed);
// define distribution: improved version of "% 4 + 1"
auto one_to_four = std::uniform_int_distribution<>(1, 4);
// generate number
auto actualNumber = one_to_four(engine);
}

I also find clock() does not give the result I want.
So I just wrote a simple Timer class to do the time duration calculation using QueryPerformanceCounter on Windows and clock_gettime on Linux
Just try this: https://github.com/AndsonYe/Timer
:)

Related

Measuring time for my array of random numbers to print is always showing 0 seconds

my first post here. Just wondering why my stopwatch is always showing 0 seconds or 0 milliseconds no matter the amount of random numbers in my array. I appreciate the help so much.
Here's my code:
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
double clock_start()
{
clock_t start = clock();
return start;
}
void random_number()
{
int array[10000];
srand(6);
cout << "10k Random numbers: ";
for (int i = 0; i < 10000; i++)
{
array[i] = rand() % 99 + 1;
cout << array[i] << "\n";
}
}
int main()
{
setlocale(LC_ALL, "");
//-------------------------//
random_number();
clock_t elapsed = (clock() - clock_start()) / (CLOCKS_PER_SEC / 1000);
cout << "Stopwatch: " << elapsed << "ms" << " or " << elapsed * 1000 << "s" << endl;
//-------------------------//
system("pause > nul");
return 0;
}
(clock() - clock_start()) will be evaluated in the blink of an eye.
All clock_start() does is return clock(). (In fact, a good optimising compiler will replace clock_start() with clock() !)
The difference will almost certainly be zero. Did you want something like
clock_t start = clock();
random_number();
clock_t elapsed = (clock() - start) / (CLOCKS_PER_SEC / 1000);
instead?
Thanks for the help guys! I'm amazed how fast this community is at replying.
So i deleted the clock_start() function. And i added the:
clock_t start = clock();
to my main function.

How do I generate any random number UNDER or ABOVE a certain number in C++?

For example, I'm making a guessing game. If the computer guesses too low, I want to send it to this function
int player1::guessLow(int g)
{
return rand() % guess + 1;
}
So that it guesses any number ABOVE what it just guessed. I also want to do the same for when it's too high
int player1::guessHigh(int g)
{
return rand() % guess - 1;
}
Obviously this isn't the correct code but how would I do this? The < and > operators don't work between in front of guess. I'm trying to come up with any random number and help the computer remember so it keeps guessing below or above that number. How would I accomplish this? Is there an algorithm or template that I can use?
UPDATE:
Here is the code
bool checkForWin(int guess, int answer)
{
cout << "You guessed " << guess << ". ";
if (answer == guess)
{
cout << "You're right! You win!" << endl;
return true;
}
else if (answer < guess)
cout << "Your guess is too high." << endl;
else
cout << "Your guess is too low." << endl;
return false;
}
void play(Player &player1, Player &player2)
{
int answer = 0, guess = 0;
answer = rand() % 100;
bool win = false;
while (!win)
{
cout << "Player 1's turn to guess." << endl;
guess = player1.getGuess();
win = checkForWin(guess, answer);
if (win) return;
cout << "Player 2's turn to guess." << endl;
guess = player2.getGuess();
win = checkForWin(guess, answer);
}
}
There are many examples of generating a random number in a given range using the standard C++ facilities. Here is a little thread-safe function to get you a number in a range:
#include <chrono>
#include <iostream>
#include <random>
long random( long min, long max )
{
// Create and initialize our PRNG
thread_local auto seed = std::chrono::system_clock::now().time_since_epoch().count();
thread_local std::ranlux48 prng( seed );
return std::uniform_int_distribution <long> ( min, max )( prng );
}
(If you are only single-threaded, you can replace thread_local with static.)
To get a range only bounded by minimum or maximum, use numeric_limits<> to find the lowest/highest value to bound with:
#include <limits>
int main()
{
std::cout << "Maximum value of 12: " << random( std::numeric_limits <long> ::min(), 12 ) << "\n";
}
Hope this helps.
rand() is part of C++ (at least for now) and is fine for a simple guessing game.
In some cases srand may not be appropriate, for example I might want repetitive behavior and predictability for testing purposes.
For this problem you may wish to use srand otherwise the guessing game gets boring.
You should completely avoid rand in many applications such as cryptography.
But here the issue is more basic. You don't need to keep track of all the numbers which you have guessed. You just have to keep track of minimum and maximum range. Example:
#include <iostream>
#include <ctime>
#include <cstdlib>
using std::cout;
int main()
{
srand((unsigned int)time(NULL));
int guess = rand();
int min = 0;
int max = RAND_MAX;
while(true)
{
int n = min + rand() % (max - min);
//(n goes up to max, not including max)
if(n < guess)
{
min = n + 1;
cout << n << " too low\n";
}
else if (n > guess)
{
max = n;
cout << n << " too high\n";
}
if(min == max)
n = min;
if(n == guess)
{
cout << n << " success\n";
break;
}
}
return 0;
}
Or use this function as suggested in comment, to find a number within a range.
int rand_rang(int min, int max)
{
if(min == max)
return min;
return min + (int)((double)rand() / ((double)RAND_MAX + 1) * (max - min));
}
These are all pseudo random numbers. If you are designing this game for a lottery corporation, then use a secure random number generator which is more difficult to crack. If distribution is very important (physics simulation etc.) then again you want to avoid rand

Using rand() to generate numbers around a variable?(C++)

I am making a small text-based game in c++ called "House Evolution" for fun. The game consists of 'searching under the couch cushions' to gain credits. When you search, the game is supposed to generate a random number anywhere from creditRate-5 to creditRate+5. How would I go about doing this using the rand() function, no matter what number creditRate is? Here is example code:
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstdlib>
#include <math.h>
int main()
{
int creditRate = 30; // Just for example.
int credits;
int searching;
while (1) {
// Yes, I know, infinite loop...
std::cout << "Credits: " << credits << std::endl;
std::cout << "Type any key to search for credits: " << std::endl;
std::cout << "Searching...\n";
usleep(10000000); // Wait 10 seconds
searching = rand(?????????); // Searching should be creditRate-5 to creditRate+5
std::cout << "You found " << searching<< " credits\n";
credits += searching;
}
}
The way I would go about it is using rand % 11, to get a range of 11 numbers and then adding it to credit rate -5 to cover the range from creditrate-5 to creditrate+5.
So:
searching = rand() % 11 + creditRate - 5;
Try:
searching = rand() % 11 + creditRate-5; That's because your range is 11 (remember, there are 11 numbers from -5 to 5, for example) and the lower limit is creditRate-5.
Use the <random> header instead of rand(), because <random> provides facilities to generate these distributions correctly instead of making you do it yourself.
#include <iostream>
#include <thread>
#include <random>
int main()
{
int creditRate = 30; // Just for example.
// Searching should be creditRate-5 to creditRate+5
std::uniform_int_distribution<> random_credit_amount(creditRate - 5, creditRate + 5);
int credits = 0;
// arrange a source of randomness
std::random_device r;
std::seed_seq seed{r(),r(),r(),r(),r(),r()};
std::mt19937 pRNG(seed);
while (true) {
// Yes, I know, infinite loop...
std::cout << "Credits: " << credits << '\n';
std::cout << "Type any key to search for credits: " << '\n';
std::cout << "Searching...\n";
std::this_thread::sleep_for(std::chrono::seconds(10)); // Wait 10 seconds
int searching = random_credit_amount(pRNG);
std::cout << "You found " << searching<< " credits\n";
credits += searching;
}
}
<random> even provides more advanced options than the typical uniform distribution. For example, instead of having every values from creditRate - 5 to creditRate + 5 be equally likely, you could have values closer to creditRate be more likely than values further away, using a 'normal' (a.k.a. 'bell curve') distribution:
// credits found should be near creditRate
std::normal_distribution<> random_credit_amount(creditRate, 5);
and then in the loop:
int searching = std::round(random_credit_amount(eng));
(You don't have to change the code in the loop at all, but it skews the distribution a bit. Performing proper rounding avoids the skew.)
Notice another change I made, replacing the non-standard usleep with the standard this_thread::sleep_for. Notice that this code makes the comment entirely redundant:
std::this_thread::sleep_for(std::chrono::seconds(10)); // Wait 10 seconds
And one can just as easily ask for sleep durations of microseconds or hours
std::this_thread::sleep_for(std::chrono::hours(2));
std::this_thread::sleep_for(std::chrono::microseconds(50));

Program is generating same random numbers on each run? [duplicate]

This question already has answers here:
Why does rand() yield the same sequence of numbers on every run?
(7 answers)
Closed 5 years ago.
I just finished coding a Minesweeper type game, and everything's good except for that each time I run the application, it generates the same number (I ran it 3 different times, saved the output to 3 text files and used the diff command in Linux, it didn't find any differences). It's seeded by time(NULL) so it should change every time, right?
Here's my code:
main.cpp
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <string>
#include "Minesweeper/box.h"
#include <cstdio>
int main(int argc, char** argv){
using namespace std;
bool gameOver = false;
int x, y, score = 0;
const int HEIGHT = 10;
const int WIDTH = 10;
unsigned int Time = time(0);
cout << "Welcome to Minesweeper. " << endl;
//setup grid
Box grid[10][10];
for(int i = 0; i < WIDTH; i++)
for(int n = 0; n < HEIGHT; n++){
unsigned int value = rand() %100 + 1;
cout << value << endl;
if(value <= 38){
grid[i][n].setFill(MINE);
//cout << i << "," << n << " is mined." << endl;
}
else
grid[i][n].setFill(EMPTY);
}
for(int r = 0; r < WIDTH; r++)
for(int l = 0; l < HEIGHT; l++)
if(grid[r][l].getFill() == EMPTY)
cout << r << "," << l << " - EMPTY." << endl;
else if (grid[r][l].getFill() == MINE)
cout << r << "," << l << " - MINE." << endl;
while(!gameOver){
cout << "Enter coordinates (x,y): ";
scanf("%i,%i",&x,&y);
if(grid[x][y].getFill() == MINE)
gameOver = true;
else{
cout << "Good job! (You chose " << x << "," << y << ")" << endl;
score++;
}
}
cout << "You hit a mine! Game over!" << endl;
cout << "Final score: " << score << endl;
getchar();
return EXIT_SUCCESS;
}
It's seeded by time(NULL)
If it is, I can't see it. In fact, a search for it in your code returns nothing. The default behaviour, if you don't explicitly seed, is the same as if you had seeded it with the value 1.
You need to explicitly state something like:
srand (time (NULL));
at the start of main somewhere (and make sure you do this once and once only).
Though keep in mind this makes it dependent on the current time - if you start multiple jobs in the same second (or whatever your time resolution is), they'll start with the same seed.
From the C standard (on which C++ is based for these compatibility features):
The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.
You need to seed randomizer. Call srand() at the beginning.
To add to the answers by others, you can use the Mersenne Twister Algorithm, which is a part of the C++11 library. Its fast becoming a standard in many common softwares to generate random numbers.
For example, this is the function I wrote, which I use often to generate random numbers in my other codes:
std::vector<double> mersennetwister(const int& My,const int& Mz,
const int& Ny,const int& Nz)
{
int ysize = (My + 2*Ny + 1);
int zsize = (Mz + 2*Nz + 1);
int matsize = ysize*zsize;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
// Seeding the generator with the system time
std::mt19937_64 generator (seed);
// Calling the Mersenne-Twister Generator in C++11
std::uniform_real_distribution<double> distribution(0,1);
// Specifying the type of distribution you want
std::vector<double> randarray(matsize,0);
// Saving random numbers to an array
for (int i=0;i<matsize;++i)
{
randarray[i] = distribution(generator); // Generates random numbers fitting the
// Distribution specified earlier
}
return(randarray);
}
Bottomline: C++11 has some excellent features for numerical operations and it would be a good idea to look into them. As for the Mersenne Twister, http://en.wikipedia.org/wiki/Mersenne_twister

How to use clock() in C++

How do I call clock() in C++?
For example, I want to test how much time a linear search takes to find a given element in an array.
#include <iostream>
#include <cstdio>
#include <ctime>
int main() {
std::clock_t start;
double duration;
start = std::clock();
/* Your algorithm here */
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout<<"printf: "<< duration <<'\n';
}
An alternative solution, which is portable and with higher precision, available since C++11, is to use std::chrono.
Here is an example:
#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
int main()
{
auto t1 = Clock::now();
auto t2 = Clock::now();
std::cout << "Delta t2-t1: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
<< " nanoseconds" << std::endl;
}
Running this on ideone.com gave me:
Delta t2-t1: 282 nanoseconds
clock() returns the number of clock ticks since your program started. There is a related constant, CLOCKS_PER_SEC, which tells you how many clock ticks occur in one second. Thus, you can test any operation like this:
clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
On Windows at least, the only practically accurate measurement mechanism is QueryPerformanceCounter (QPC). std::chrono is implemented using it (since VS2015, if you use that), but it is not accurate to the same degree as using QueryPerformanceCounter directly. In particular it's claim to report at 1 nanosecond granularity is absolutely not correct. So, if you're measuring something that takes a very short amount of time (and your case might just be such a case), then you should use QPC, or the equivalent for your OS. I came up against this when measuring cache latencies, and I jotted down some notes that you might find useful, here;
https://github.com/jarlostensen/notesandcomments/blob/master/stdchronovsqcp.md
#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep() --- just a function that waits a certain amount of milliseconds
using namespace std;
int main()
{
clock_t cl; //initializing a clock type
cl = clock(); //starting time of clock
_sleep(5167); //insert code here
cl = clock() - cl; //end point of clock
_sleep(1000); //testing to see if it actually stops at the end point
cout << cl/(double)CLOCKS_PER_SEC << endl; //prints the determined ticks per second (seconds passed)
return 0;
}
//outputs "5.17"
You can measure how long your program works. The following functions help measure the CPU time since the start of the program:
C++ (double)clock() / CLOCKS_PER_SEC with ctime included.
Python time.clock() returns floating-point value in seconds.
Java System.nanoTime() returns long value in nanoseconds.
My reference: algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics
So you can add this line of code after your algorithm:
cout << (double)clock() / CLOCKS_PER_SEC;
Expected Output: the output representing the number of clock ticks per second
Probably you might be interested in timer like this :
H : M : S . Msec.
the code in Linux OS:
#include <iostream>
#include <unistd.h>
using namespace std;
void newline();
int main() {
int msec = 0;
int sec = 0;
int min = 0;
int hr = 0;
//cout << "Press any key to start:";
//char start = _gtech();
for (;;)
{
newline();
if(msec == 1000)
{
++sec;
msec = 0;
}
if(sec == 60)
{
++min;
sec = 0;
}
if(min == 60)
{
++hr;
min = 0;
}
cout << hr << " : " << min << " : " << sec << " . " << msec << endl;
++msec;
usleep(100000);
}
return 0;
}
void newline()
{
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}