Making a Timer in c++? - c++

I am developing a simple game in c++, a chase-the-dot style one, where you must click a drawn circle on the display and then it jumps to another random location with every click, but I want to make the game end after 60 seconds or so, write the score to a text file and then upon launching the program read from the text file and store the information into an array and somehow rearrange it to create a high score table.
I think I can figure out the high score and mouse clicking in a certain area myself, but I am completely stuck with creating a possible timer.
Any help appreciated, cheers!

In C++11 there is easy access to timers. For example:
#include <chrono>
#include <iostream>
int main()
{
std::cout << "begin\n";
std::chrono::steady_clock::time_point tend = std::chrono::steady_clock::now()
+ std::chrono::minutes(1);
while (std::chrono::steady_clock::now() < tend)
{
// do your game
}
std::cout << "end\n";
}
Your platform may or may not support <chrono> yet. There is a boost implementation of <chrono>.

Without reference to a particular framework or even the OS this is unanswerable.
In SDL there is SDL_GetTicks() which suits the purpose.
On linux, there is the general purpose clock_gettime or gettimeofday that should work pretty much everywhere (but beware of the details).
Win32 API has several function calls related to this, including Timer callback mechanisms, such as GetTickCount, Timers etc. (article)
Using timers is usually closely related to the meme of 'idle' processing. So you'd want to search for that topic as well (and this is where the message pump comes in, because the message pump decides when (e.g.) WM_IDLE messages get sent; Gtk has a similar concept of Idle hooks and I reckon pretty much every UI framework does)

Usually GUI program has so called "message pump" loop. Check of that timer should be a part of your loop:
while(running)
{
if( current_time() > end_time )
{
// time is over ...
break;
}
if( next_ui_message(msg) )
dispatch(msg);
}

Try this one out:
//Creating Digital Watch in C++
#include<iostream>
#include<Windows.h>
using namespace std;
struct time{
int hr,min,sec;
};
int main()
{
time a;
a.hr = 0;
a.min = 0;
a.sec = 0;
for(int i = 0; i<24; i++)
{
if(a.hr == 23)
{
a.hr = 0;
}
for(int j = 0; j<60; j++)
{
if(a.min == 59)
{
a.min = 0;
}
for(int k = 0; k<60; k++)
{
if(a.sec == 59)
{
a.sec = 0;
}
cout<<a.hr<<" : "<<a.min<<" : "<<a.sec<<endl;
a.sec++;
Sleep(1000);
system("Cls");
}
a.min++;
}
a.hr++;
}
}
See the details at: http://www.programmingtunes.com/creating-timer-c/#sthash.j9WLtng2.dpuf

Related

How can I watch multiple variables while debugging without stopping at breakpoints?

Suppose I have a complex C++ application that I need to debug with a lot of variables. I wanna avoid using std::cout and printf approaches (below there's an explaination why).
In order to explain my issue, I wrote a minimal example using chrono (This program calculates fps of its while cycle over time and increment i_times counter until it reaches 10k):
#include <chrono>
using chrono_hclock = std::chrono::high_resolution_clock;
int main(int argc, char** argv){
bool is_running = true;
float fps;
int i_times=0;
chrono_hclock::time_point start;
chrono_hclock::time_point end;
while(is_running){
start = chrono_hclock::now();
// Some code execution
end = chrono_hclock::now();
fps=(float)1e9/(float)std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count());
if(++i_times==10000) is_running=false;
}
return 0;
}
I would like to debug this program and watch for fps and i_times variables continuosly over time, without stopping execution.
Of course I can simply use std::cout, printf or other means to output variables values redirecting them to stdout or a file while debugging and those are OK for simple types, but I have multiple variables which data type are struct-based and it would be creepy, time expensive and code bloating to write instructions to print each one of them. Also my application is a realtime video/audio H.264 encoder streaming with RTSP protocol and stopping at breakpoints means visualizing artifacts in my other decoder application because the encoder can't keep up with the decoder (because the encoder hit a breakpoint).
How can I solve this issue?
Thanks and regards!
The IDE I'm currently using for developing is Visual Studio 2019 Community.
I'm using the Local Windows Debugger.
I'm open to using alternative open source IDEs like VSCode or alternative debugging methods to solve this problem and/or to not be confinated into using a specific IDE.
To watch for specific multiple variables in VS I use the built-in Watch Window. While debugging with LWD, I add manually variables by right-clicking them in my source code and click Add Watch. Then those are showed in the Watch Window (Debug-Windows-Watch-Watch 1):
However I can only watch this window contents once I hit a breakpoint I set inside the while cycle, thus blocking execution, so that doesn't solve my issue.
You can use nonblocking breakpoint. First add the breakpoint. Then click on breakpoint settings or right click and select action.
Now you add a message like any string that is suggestive for you. And in brackets include the values to show, for instance
value of y is {y} and value of x is {x}
In the image is shown the value of i when it hits the breakpoint. Check the "Continue code execution" so breakpoint will not block execution. The shape of your breakpoint will change to red diagonal square. You can add also specific conditions if you click the Conditions checkbox.
Now while debugging all these debug messages will be shown in the output window:
In the above image it is showing the following message:
the value of i is {i}
By checking the "Conditions" you can add specific conditions, for instance i%100==0 and it will show the message only if i is divisible by 100.
This time your breakpoint will be marked with a + sign, meaning it has condition. Now while debugging there will be shown the i only when divisible by 100, so you can restrict the output to some more meaningful cases
The strict answer is "no" but...
I think I understand what you're trying to accomplish. This could be done by dumping the watched variables into to shared memory which is read by 2nd process. A watch and a break point in the 2nd would allow you to see the values in Visual Studio without interrupting the original application.
A few caveats:
UAC must be admin on both sides to open the memory handle
This wouldn't work with pointers as the 2nd program only has access to the shared memory
Windows anti-virus went nuts for the first few times I
ran this but eventually calmed down
Worker application:
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <windows.h>
#include <chrono>
#include <thread>
PCWSTR SHARED_MEMORY_NAME = L"Global\\WatchMemory";
struct watch_collection // Container for everything we want to watch
{
int i;
int j;
int k;
};
using chrono_hclock = std::chrono::high_resolution_clock;
int main(int argc, char** argv)
{
bool is_running = true;
float fps;
int i_times = 0;
chrono_hclock::time_point start;
chrono_hclock::time_point end;
HANDLE map_file;
void* shared_buffer;
// Set up the shared memory space
map_file = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(watch_collection), SHARED_MEMORY_NAME);
if (map_file == NULL)
{
return 1; // Didn't work, bail. Check UAC level!
}
shared_buffer = MapViewOfFile(map_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(watch_collection));
if (shared_buffer == NULL)
{
CloseHandle(map_file); // Didn't work, clean up the file handle and bail.
return 1;
}
// Do some stuff
while (is_running) {
start = chrono_hclock::now();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 10000; j++)
{
for (int k = 0; k < 10000; k++) {
watch_collection watches { i = i, j = j, k = k };
CopyMemory(shared_buffer, (void*)&watches, (sizeof(watch_collection))); // Copy the watches to the shared memory space
// Do more things...
}
}
}
end = chrono_hclock::now();
fps = (float)1e9 / (float)std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
if (++i_times == 1000000) is_running = false;
}
// Clean up the shared memory buffer and handle
UnmapViewOfFile(shared_buffer);
CloseHandle(map_file);
return 0;
}
Watcher application:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")
PCWSTR SHARED_MEMORY_NAME = L"Global\\WatchMemory";
struct watch_collection // Container for everything we want to watch
{
int i;
int j;
int k;
};
int main()
{
HANDLE map_file;
void* shared_buffer;
bool is_running = true;
watch_collection watches; // Put a watch on watches
// Connect to the shared memory
map_file = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, SHARED_MEMORY_NAME);
if (map_file == NULL)
{
return 1; // Couldn't open the handle, bail. Check UAC level!
}
shared_buffer = MapViewOfFile(map_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(watch_collection));
if (shared_buffer == NULL)
{
CloseHandle(map_file);
return 1;
}
// Loop forever
while (is_running)
{
CopyMemory((void*)&watches, shared_buffer, (sizeof(watch_collection)));
} // Breakpoint here
UnmapViewOfFile(shared_buffer);
CloseHandle(map_file);
return 0;
}

C++ using proccesing power/time while console loading bar

I'm currently new to programming and don't know, how to let the program process while the loading bar is running.
I wanted to display the loading bar and check, wether the program is finished processing. If not, then the processing bar should simply begin to fill again.
My code now is just showing the loading bar once and begins to process after that. This is pretty useless.
I researched on Google and here on stack overflow, but i only got the loading bar from that, not the useful integration in my program.
I just need a simple way to check, wether there would be an output besides the loading bar and i need to run the rest of the program at the same time as the loading bar, just to save time.
#include <iostream>
#include <windows.h>
#include <unistd.h>
#include <string>
#include <thread>
using namespace std;
static void loading(){
system("Color 0A");
cout<<"\t\n\n";
char a=177, b=219;
cout<<"\t";
for (int i=0;i<=50;i++)
cout<<a;
cout<<"\r";
cout<<"\t";
for (int i=0;i<=50;i++){
cout<<b;
for (int j=0;j<=2e7;j++);
}
cout << "\n\n";
}
int main(){
//ProjectEuler Problem___
loading();
int j=0;
do{
j++;
}while(j<=1e9); //just an example to see when it is processing
cout << "hi" << endl;
return 0;
}
I'm grateful for any help.
The typical pattern you're looking for would look something like:
void do_expensive_work(std::atomic<bool>& done) {
... something expensive goes here...
done = true;
}
int main() {
std::atomic<bool> done = false;
auto t = std::thread(do_expensive_work, std::ref(done));
while (!done) {
... update your progress bar ...
... sleep a bit ...
}
t.join();
return 0;
}
The specifics of how you communicate the result of your computation back to the calling thread etc are up to you. Similarly, you could in theory use a global atomic for the done status, or wrap up the computation in a class that keeps track of state and manages the execution of the thread. Code above is greatly simplified but gives a general pattern.

Arduino getting stuck in simple C++ function

I am currently working on a little Arduino project, which is using an infrared temperature sensor for measuring certain surface temperatures.
The hardware works perfectly and also simply reading analog signals with analogRead() works fine, but using this simple function for filtering the measured analog values to get better results just doesn't get along with the Arduino.
Every time the sketch running this function is uploaded to the Arduino (Pro Micro), the program just gets stuck and disables the Arduino, so that it has to be reset before appearing again in the "Ports" Menu as a COM Port.
Here is the simple function in which I cannot find the bug:
int TemperatureDifferenceSensor::measureRawFilteredTemperatureValue(int numberOfMeasurements) {
int temperatureMeasurementValueSum = 0;
int maxMeasuredTempValue = 0;
int minMeasuredTempValue = 0;
for (int i = 0; i < numberOfMeasurements; ++i) {
int measuredTemperatureValue = analogRead(analogObjectTempPin);
temperatureMeasurementValueSum += measuredTemperatureValue;
if (measuredTemperatureValue > maxMeasuredTempValue) {
maxMeasuredTempValue = measuredTemperatureValue;
} else if (measuredTemperatureValue < minMeasuredTempValue) {
minMeasuredTempValue = measuredTemperatureValue;
}
// A small delay, to not measure the same or similar value every time...
delay(10);
}
temperatureMeasurementValueSum -= maxMeasuredTempValue;
temperatureMeasurementValueSum -= minMeasuredTempValue;
int temperatureMeasurementAverageValue = (int) (temperatureMeasurementValueSum / (numberOfMeasurements - 2));
return temperatureMeasurementAverageValue;
}
If analogRead and delay works as you expected, it should be somewhat ok. One big issue with the function is that it can't be called with argument 2. This would cause zero-division exception and probably also a black hole. Why not something like:
...
} // the for-loop closes here.
if (numberOfMeasurements == 0)
return 0;
// Must have at least 3 measurements in order to remove 2 of them.
else if (numberOfMeasurements > 2)
{
temperatureMeasurementValueSum -= maxMeasuredTempValue;
temperatureMeasurementValueSum -= minMeasuredTempValue;
numberOfMeasurements -= 2; // Compensate removing two measurements.
}
// Average is sum divided by measurements.
int temperatureMeasurementAverageValue = temperatureMeasurementValueSum / numberOfMeasurements;
return temperatureMeasurementAverageValue;

Window Hangs And Freezes [SDL 2]

I have a text file full of information on where to place tiles in a game i'm making, the fastest way to access this information is with a for loop. But whenever i use the for loop to get through all the information it freezes the program for about 12 seconds, in those 12 i cant move the window, nothing on the renderer updates/is drawn, and then when i click on the window it breaks and says "window name (Not Responding)". I tried using a while loop but it still does the same thing.
How can i loop through bigger numbers (there are about 4,000 tiles in the level) without the program freezing/hanging on me? I'm just using SDL 2, no OpenGL involved.
int tiles = 4000;
int x[4000];
int y[4000];
tile obj[4000];
for(int i = 0; i < tiles; i++)
{
x[i] = txt.x;
y[i] = txt.y;
obj[i].Load(x[i], y[i]);
obj[i].Add();
SDL_RenderClear(ren);
LoadScreen();
SDL_RenderPresent(ren);
}
Thanks.
You need to create another thread.
It's good idea to wait for all data to load before starting game, so during load, you don't need to render anything. Even with this approach, it is better to use another thread and don't keep "UI Thread" busy. During load time your UI would be mostly disabled except a cancel button that will stop loading thread.
#include <process.h>
bool bReady;
void LoadTiles(void* pArg)
{
// Load Data here
*((int*)pArg) = 0;
///////////////////
bReady = true;
}
void main()
{
btnStart.SetEnabled(false);
bReady = false;
int iTarget;
uintptr_t hLoadingThread = _beginthread(LoadTiles, 0, &iTarget);
while (true) // usually you pick a message here
{
if (bReady)
btnStart.SetEnabled(true);
}
}
This is just a very simple example, multi-threading needs a lot of work and study!

How to stop a function from running from outside in c++

I want to run a function and tell if the function didn't finish after n milliseconds, stop that function and start another one. something like this code:
void run()
{
//do something that doesn't have while(1)
}
void main()
{
run();
if(runFunctionDidntFinishInSeconds(10)
{
endPrintFunction();
backupPlan();
}
return 0;
}
I searched out and found boost::timed_join function. here's my code:
void run()
{
int a;
for (int i = 0; i < 2000; i++)
cout << i << endl;
}
int main()
{
boost::thread t = new boost::thread(&run);
if (t.timed_join(boost::posix_time::microseconds(10000))){
cout << "done" << endl;
}
else{
cout << endl << "not done" << endl;
}
system("pause");
return 0;
}
but it doesn't stop thread 't' from running. I went to terminate the thread, but it's not a good option.
I want the 'a' function to finish the exact time I'm telling it to.
The system gets input every 16ms and I want to do a processing on it and say if the processing took more than about 13ms leave it and go do a backup plan. and I want it to be abstracted from the ones who write the processing method. So putting a while loop on the top of it brings me delay.
What should i do?
The least I think I need is to be abled to reset the processing thread to do what it had needed to do again!
I think your are looking for something like std::future.
http://en.cppreference.com/w/cpp/thread/future/wait_for
You can start the function in another thread and wait until the function returns or has a timeout.
For your example:
std::future< void > future = std::async( std::launch::async, print );
auto status = future.wait_for( std::chrono::seconds( 10 ) );
if ( status == std::future_status::deferred )
{
std::cout << "deferred\n";
}
else if ( status == std::future_status::timeout )
{
std::cout << "timeout\n";
}
else if ( status == std::future_status::ready )
{
std::cout << "ready!\n";
}
However this doesn't cause the detached thread to end. For this it is necessary to include a flag on startup, so the detached thread can cleanup and exit savely on its own.
void run(const std::atomic_bool& cancelled)
{
int a;
for (int i = 0; i < 2000; i++)
{
cout << i << endl;
if (cancelled)
return;
}
}
std::atomic_bool cancellation_token = false;
std::future< void > future = std::async( std::launch::async,
run,
std::ref(cancellation_token) );
auto status = future.wait_for( std::chrono::seconds( 10 ) );
if ( status == std::future_status::deferred )
{
std::cout << "deferred\n";
}
else if ( status == std::future_status::timeout )
{
std::cout << "timeout\n";
cancellation_token = true;
}
else if ( status == std::future_status::ready )
{
std::cout << "ready!\n";
}
I want it to be abstracted from the ones who write the processing method.
Standard C++ does not have a way to forcibly interrupt the control flow of a function from outside of that function's call graph (a function it calls can throw, but someone can't throw for them).
OS-specific thread systems have ways to terminate a thread. However, this leaves the program potentially in an undefined state, as the destructors for any stack variables have not been called. And since you didn't know where it was in that processing when you killed it, you can't effectively clean up after it. Even a C program cannot guarantee that an arbitrary function can be terminated; it would have to be one which did not dynamically allocate memory or other resources that have to be cleaned up.
You can compensate for this by coding your function very carefully. But that requires that the person who wrote that function to code it very carefully. And thus, there isn't an abstraction, since the person writing the function has to know what the rules are and is required to follow them.
So the only solution that works requires cooperation. The function must either be written in such a way that it can safely be stopped via those OS-dependent features, or it must be written to periodically check some value and stop itself.
Here are two and 3/4 approaches.
The first requires that the code you want to halt cooperates. It either polls some variable while it runs, or it calls a function periodically that could throw an exception to halt execution. boost interruptable threads follow the second model.
The second requires you to launch a new process, marshall your data over to the function, and use IPC to get the information back. If the function doesn't return in time, you kill the child process.
The third "half" involves rewriting the code in a different language, or using C++ as a scripting language. You run the code in an interpreter that does the first or second solution for you.
Now, a practical alternative (a 1/4 solution) is to make sure the function is purely functional, run it in a separate thread with a semi-reliable abort message (like the first one), and discard its return value if it takes too long. This doesn't do what you want, but is far easier.
There's a way with atomics used as semaphores but this will emit full blown memory barriers and thus decrease the performance because of the load every iteration :
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
std::atomic<bool> printFinished { false };
std::atomic<bool> shouldPrintRun { true };
void print()
{
while (shouldPrintRun.load() /* && your normal stop condition*/)
{
//work..
}
printFinished.store(true);
}
int main()
{
std::thread t(print);
std::this_thread::sleep_for(std::chrono::seconds(10));
if (!printFinished.load())
{
shouldPrintRun.store(false);
t.join();
std::cout << "help!";
}
return 0;
}
If you don't want your function that's ran on another thread to check back if it needs to stop then terminating that thread is the only option.
A possible solution is that you have to make that the lengthy function into small & short incremental function which will continue the task still every time it is call from the last time it left of. The code below which can be run in a thread will do similar job of a time slicer and can be terminated at will.
void Process()
{
bool flag = true;
while (running)
{
std::chrono::high_resolution_clock::time_point time1 = std::chrono::high_resolution_clock::now();
std::chrono::milliseconds span(16);
while ( (std::chrono::high_resolution_clock::now() - time1 ) < span)
{
flag ? incremental_function1() : incremental_function2();
if (!running) return;
}
flag = (!flag);
}
}