I am teaching myself programming, and as a challenge I tried making a simple text battle system in c++. I used the function rand() to generate pseudo-random numbers. The problem is, they were the same every time you ran the program. e.g. If num1 was in the first turn 1, on the second 0, then 0, 1, 0, 1, 1, 1 etc, if you closed the program and reopened it, it would always be 1, 0, 0, 1, 0, 1, 1, 1...
I then looked up how to measure time. I wanted to take an integer expressing exactly how long it took the player to enter a certain string. I followed the tutorials precisely (except I named the variables differently). It did not work. Can anyone please help me and explain how the syntax of this works? I put together a simple program representing exactly what I did, so that you don't have to go through the long, irrelevant code of the entire battle system. I looked up questions like this but nothing worked yet.
#include <iostream>
#include <chrono>
using namespace std;
int main()
{
auto time1 = std::chrono::high_resolution_clock::now();
cout << "enter a character:" << endl;
char blob;
cin >> blob;
auto time2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> time = timer2 - timer1;
cout << time;
return 0;
}
if you wont to use rand() function you need first to call srand with "seed"
this is an example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int i, n;
time_t t;
n = 5;
/* Intializes random number generator */
srand((unsigned) time(&t));
/* Print 5 random numbers from 0 to 50 */
for( i = 0 ; i < n ; i++ ) {
printf("%d\n", rand() % 50);
}
return(0);
}
but like people wrote in the comment is c style code not CPP
this is use with CPP
#include <random>
#include <iostream>
int main()
{
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]
std::cout << dist6(rng) << std::endl;
}
How to generate a random number in C++?
Your code does not work as you expected due to 3 reasons:
Typo in variable names: change timer1 and timer2 to time1 and time2 respectively.
Use duration_cast instead of duration.
Use count() method.
count() returns the number of ticks of the type on which you invoke
it.
Here is the finished code:
#include <iostream>
#include <chrono>
using namespace std;
int main()
{
// meausure time at the begining.
auto time1 = chrono::high_resolution_clock::now();
cout << "enter a character:" << endl;
char blob;
// wait for user input.
cin >> blob;
// meausure time at the ending.
auto time2 = chrono::high_resolution_clock::now();
// evaluate and print the difference.
auto time = chrono::duration_cast<chrono::milliseconds>(time2 - time1);
cout << time.count();
return 0;
}
But, as #yaodav suggested, there are other better ways to generate random numbers in C++.
Related
What I want to do, my project:
I want to make a program that waits 0.5 seconds, for example, does something, let's say cout << "Hello World", once and then again the same for about 10 times(this is a test for another program), but without sleep, sleep_for, sleep or anything similar BCS I don't want the processor to actually sleep, BCS at that time the processor does not just wait, it does nothing for that time, for these 0.5 seconds it does nothing and I don't want that, and the main reason is BCS it also doesn't take input.
What I tried:
What I tried was to keep two points in time(time_point start,end), duration_cast their difference (end - start) in a for loop ((int i = 0;i < 10;i++)), and if their difference was 500 milliseconds, then, cout << "Hello World\n";.
My code looked something like this:
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace chrono;
int main()
{
time_point<steady_clock> t = steady_clock::now():
for (int i = 0; i < 10;)
{
duration<double> d = steady_clock::now() - t;
uint32_t a = duration_cast<milliseconds>(d).count();
if (a >= 500)
{
cout << a << " Hello World!" << endl;
t = steady_clock::now();
i++;
}
}
return 0;
}
My problem:
It overflows, most of the time, I don't know what exactly overflows, but a appears to be sometimes 6??? others 47??? (? = some digit)
I tried many things, I ended up to something like this:
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace chrono;
int main()
{
time_point<high_resolution_clock> t = high_resolution_clock::now();
for (int i = 0; i< 10;)
{
duration<double,ratio<1,1000000>> d = high_resolution_clock::now() - t;
uint32_t a = duration_cast<microseconds>(d).count();
if (d >= microseconds(500000) )
{
cout << a << " Hello World!" << endl;
i++;
t = high_resolution_clock::now();
}
}
return 0;
}
It didn't really solve the problem, but the max value appears is `~1500(1500000 in microseconds) and when it happens it takes longer to print the message, I don't know if its still overflow, to be honest, but...
Question
Anyway, do you have any suggestions about how to stop the overflow or a completely different way to achieve what I want, even if you don't, thanks for spending time to read my question, I hope to express someone else's question if there someone who has the same question as me.
Not sure if this is what you're looking for or not. But if not, maybe we can build on this to figure out what you want:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
auto t = steady_clock::now();
for (int i = 0; i < 10; ++i)
{
auto t1 = t + 500ms;
while (steady_clock::now() < t1)
;
cout << duration<double>(t1-t).count() << " Hello World!" << endl;
t = t1;
}
}
The code sets a time_point for 500ms in the future, and then enters a busy loop until that future time_point is now.
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));
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
:)
I have written a c++ program , I want to know how to calculate the time taken for execution so I won't exceed the time limit.
#include<iostream>
using namespace std;
int main ()
{
int st[10000],d[10000],p[10000],n,k,km,r,t,ym[10000];
k=0;
km=0;
r=0;
scanf("%d",&t);
for(int y=0;y<t;y++)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
cin>>st[i] >>d[i] >>p[i];
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if((d[i]+st[i])<=st[j])
{
k=p[i]+p[j];
}
if(k>km)
km=k;
}
if(km>r)
r=km;
}
ym[y]=r;
}
for( int i=0;i<t;i++)
{
cout<<ym[i]<<endl;
}
//system("pause");
return 0;
}
this is my program and i want it to be within time limit 3 sec !! how to do it ?
yeah sorry i meant execution time !!
If you have cygwin installed, from it's bash shell, run your executable, say MyProgram, using the time utility, like so:
/usr/bin/time ./MyProgram
This will report how long the execution of your program took -- the output would look something like the following:
real 0m0.792s
user 0m0.046s
sys 0m0.218s
You could also manually modify your C program to instrument it using the clock() library function, like so:
#include <time.h>
int main(void) {
clock_t tStart = clock();
/* Do your stuff here */
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
With C++11 for measuring the execution time of a piece of code, we can use the now() function:
auto start = chrono::steady_clock::now();
// Insert the code that will be timed
auto end = chrono::steady_clock::now();
// Store the time difference between start and end
auto diff = end - start;
If you want to print the time difference between start and end in the above code, you could use:
cout << chrono::duration <double, milli> (diff).count() << " ms" << endl;
If you prefer to use nanoseconds, you will use:
cout << chrono::duration <double, nano> (diff).count() << " ns" << endl;
The value of the diff variable can be also truncated to an integer value, for example, if you want the result expressed as:
diff_sec = chrono::duration_cast<chrono::nanoseconds>(diff);
cout << diff_sec.count() << endl;
For more info click here
OVERVIEW
I have written a simple semantic hack for this using #AshutoshMehraresponse. You code looks really readable this way!
MACRO
#include <time.h>
#ifndef SYSOUT_F
#define SYSOUT_F(f, ...) _RPT1( 0, f, __VA_ARGS__ ) // For Visual studio
#endif
#ifndef speedtest__
#define speedtest__(data) for (long blockTime = NULL; (blockTime == NULL ? (blockTime = clock()) != NULL : false); SYSOUT_F(data "%.9fs", (double) (clock() - blockTime) / CLOCKS_PER_SEC))
#endif
USAGE
speedtest__("Block Speed: ")
{
// The code goes here
}
OUTPUT
Block Speed: 0.127000000s
Note: the question was originally about compilation time, but later it turned out that the OP really meant execution time. But maybe this answer will still be useful for someone.
For Visual Studio: go to Tools / Options / Projects and Solutions / VC++ Project Settings and set Build Timing option to 'yes'. After that the time of every build will be displayed in the Output window.
You can try below code for c++:
#include <chrono>
auto start = std::chrono::system_clock::now();
// Your Code to Execute //
auto end = std::chrono::system_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;
This looks like Dijstra's algorithm. In any case, the time taken to run will depend on N. If it takes more than 3 seconds there isn't any way I can see of speeding it up, as all the calculations that it is doing need to be done.
Depending on what problem you're trying to solve, there might be a faster algorithm.
I have used the technique said above, still I found that the time given in the Code:Blocks IDE was more or less similar to the result obtained-(may be it will differ by little micro seconds)..
If you are using C++ then you should try this below code as you would always get 0 as answer if you directly use #Ashutosh Mehra's answer.
#include <iostream>
#include <time.h>
using namespace std;
int main() {
int a = 20000, sum=0;
clock_t start = clock();
for (int i=0; i<a; i++) {
for (int k = 0; k<a; k++)
sum += 1;
}
cout.precision(10);
cout << fixed << float(clock() - start)/CLOCKS_PER_SEC << endl;
return 0;
}
Because in C++ you the float and double values will directly be rounded off. So I used the cout.precision(10) to set the output precision of any value to 10 digits after decimal.
shorter version of Ashutosh Mehra's answer:
/* including stuff here */
#include <time.h>
int main(void) {
clock_t tStart = clock();
/* stuff here */
cout<<"Time taken: "<<(double)(clock() - tStart)/CLOCKS_PER_SEC;
return 0;
}
I want to measure the speed of a function within a loop. But why my way of doing it always print "0" instead of high-res timing with 9 digits decimal precision (i.e. in nano/micro seconds)?
What's the correct way to do it?
#include <iomanip>
#include <iostream>
#include <time.h>
int main() {
for (int i = 0; i <100; i++) {
std::clock_t startTime = std::clock();
// a very fast function in the middle
cout << "Time: " << setprecision(9) << (clock() - startTime + 0.00)/CLOCKS_PER_SEC << endl;
}
return 0;
}
Related Questions:
How to overcome clock()'s low resolution
High Resolution Timer with C++ and linux
Equivalent of Windows’ QueryPerformanceCounter on OSX
Move your time calculation functions outside for () { .. } statement then devide total execution time by the number of operations in your testing loop.
#include <iostream>
#include <ctime>
#define NUMBER 10000 // the number of operations
// get the difference between start and end time and devide by
// the number of operations
double diffclock(clock_t clock1, clock_t clock2)
{
double diffticks = clock1 - clock2;
double diffms = (diffticks) / (CLOCKS_PER_SEC / NUMBER);
return diffms;
}
int main() {
// start a timer here
clock_t begin = clock();
// execute your functions several times (at least 10'000)
for (int i = 0; i < NUMBER; i++) {
// a very fast function in the middle
func()
}
// stop timer here
clock_t end = clock();
// display results here
cout << "Execution time: " << diffclock(end, begin) << " ms." << endl;
return 0;
}
Note: std::clock() lacks sufficient precision for profiling. Reference.
A few pointers:
I would be careful with the optimizer, it might throw all your code if I will think that it doesn't do anything.
You might want to run the loop 100000 times.
Before doing the total time calc store the current time in a variable.
Run your program several times.
If you need higher resolution, the only way to go is platform dependent.
On Windows, check out the QueryPerformanceCounter/QueryPerformanceFrequency API's.
On Linux, look up clock_gettime().
See a question I asked about the same thing: apparently clock()'s resolution is not guaranteed to be so high.
C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly
Try gettimeofday function, or boost
If you need platform independence you need to use something like ACE_High_Res_Timer (http://www.dre.vanderbilt.edu/Doxygen/5.6.8/html/ace/a00244.html)
You might want to look into using openMp.
#include <omp.h>
int main(int argc, char* argv[])
{
double start = omp_get_wtime();
// code to be checked
double end = omp_get_wtime();
double result = end - start;
return 0;
}