I am trying to create a timer where it begins with a certain value and ends with another value like.
int pktctr = (unsigned char)unpkt[0];
if(pktctr == 2)
{
cout << "timer-begin" << endl;
//start timer here
}
if(pktctr == 255)
{
cout << "timer-end" << endl;
//stop timer here
//timer display total time then reset.
}
cout << "displays total time it took from 1 to 255 here" << endl;
Any idea on how to achieve this?
void WINAPI MyUCPackets(char* unpkt, int packetlen, int iR, int arg)
{
int pktctr = (unsigned char)unpkt[0];
if(pktctr == 2)
{
cout << "timer-begin" << endl;
}
if(pktctr == 255)
{
cout << "timer-end" << endl;
}
return MyUC2Packets(unpkt,packetlen,iR,arg);
}
Everytime this function is called unpkt starts from 2 then reaches max of 255 then goes back to 1. And I want to compute how long it took for every revolution?
This will happen alot of times. But I just wanted to check how many seconds it took for this to happen because it won't be the same everytime.
Note: This is done with MSDetours 3.0...
I'll assume you're using Windows (from the WINAPI in the code) in which case you can use GetTickCount:
/* or you could have this elsewhere, e.g. as a class member or
* in global scope (yuck!) As it stands, this isn't thread safe!
*/
static DWORD dwStartTicks = 0;
int pktctr = (unsigned char)unpkt[0];
if(pktctr == 2)
{
cout << "timer-begin" << endl;
dwStartTicks = GetTickCount();
}
if(pktctr == 255)
{
cout << "timer-end" << endl;
DWORD dwDuration = GetTickCount() - dwStartTicks;
/* use dwDuration - it's in milliseconds, so divide by 1000 to get
* seconds if you so desire.
*/
}
Things to watch out for: overflow of GetTickCount is possible (it resets to 0 approximately every 47 days, so it's possible that if you start your timer close to the rollover time, it will finish after the rollover). You can solve this in two ways, either use GetTickCount64 or simply notice when dwStartTicks > GetTickCount and if so, calculate how many milliseconds were from dwStartTicks until the rollover, and how many millseconds from 0 to the result of GetTickCount() and add those numbers together (bonus points if you can do this in a more clever way).
Alternatively, you can use the clock function. You can find out more on that, including an example of how to use it at http://msdn.microsoft.com/en-us/library/4e2ess30(v=vs.71).aspx and it should be fairly easy to adapt and integrate into your code.
Finally, if you're interested in a more "standard" solution, you can use the <chrono> stuff from the C++ standard library. Check out http://en.cppreference.com/w/cpp/chrono for an example.
If you want to use the Windows-API use GetSystemTime(). Provide a struct SYSTEMTIME, initialize it properly and pass it to GetSystemTime():
#include <Windows.h>
...
SYSTEMTIME sysTime;
GetFileTime(&sysTime);
// use sysTime and create differences
Look here for GetSystemTime() there is a link for SYSTEMTIME there, too.
I think boost timer is the best solution for you.
You can check the elapsed time like this:
#include <boost/timer.hpp>
int main() {
boost::timer t; // start timing
...
double elapsed_time = t.elapsed();
...
}
Related
I made a factoring program that needs to loop as quickly as possible. However, I also want to track the progress with minimal code. To do this, I display the current value of i every second by comparing time_t start - time_t end and an incrementing value marker.
using namespace std; // cause I'm a noob
// logic stuff
int divisor = 0, marker = 0;
int limit = sqrt(num);
for (int i = 1; i <= limit; i++) // odd number = odd factors
{
if (num % i == 0)
{
cout << "\x1b[2K" << "\x1b[1F" << "\x1b[1E"; // clear, up, down
if (i != 1)
cout << "\n";
divisor = num / i;
cout << i << "," << divisor << "\n";
}
end = time(&end); // PROBLEM HERE
if ((end - start) > marker)
{
cout << "\x1b[2K" << "\x1b[1F" << "\x1b[1E"; // clear, up, down
cout << "\t\t\t\t" << i;
marker++;
}
}
Of course, the actual code is much more optimized and uses boost::multiprecision, but I don't think that's the problem. When I remove the line end = time(&end), I see a performance gain of at least 10%. I'm just wondering, how can I track the time (or at least approximate seconds) without unconditionally calling a function every loop? Or is there a faster function?
You observe "When I remove the line end = time(&end), I see a performance gain of at least 10%." I am not surprised, reading time easily is taking inefficient time, compared to doing pure CPU calculations.
I assume hence that the time reading is actually what eats the performance which observe lost when removing the line.
You could use an estimation of the minimum number of iterations your loop does within a second and then only check the time if multiples of (half of) that number have looped.
I.e., if you only want to be aware of time in a resolution of seconds, then you should try to only marginally more often do the time-consuming reading of the time.
I would use a totally different approach where you seperate measurement/display code from the loop completely and even run it on another thread.
Live demo here : https://onlinegdb.com/8nNsGy7EX
#include <iostream>
#include <chrono> // for all things time
#include <future> // for std::async, that allows us to run functions on other threads
void function()
{
const std::size_t max_loop_count{ 500 };
std::atomic<std::size_t> n{ 0ul }; // make access to loopcounter threadsafe
// start another thread that will do the reporting independent of the
// actual work you are doing in your loop.
// for this capture n (loop counter) by reference (so this thread can look at it)
auto future = std::async(std::launch::async,[&n, max_loop_count]
{
while (n < max_loop_count)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "\rprogress = " << (100 * n) / max_loop_count << "%";
}
});
// do not initialize n here again. since we share it with reporting
for (; n < max_loop_count; n++)
{
// do your loops work, just a short sleep now to mimmick actual work
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// synchronize with reporting thread
future.get();
}
int main()
{
function();
return 0;
}
If you have any questions regarding this example let me know.
I want to know how to properly implement a program in C++, in which I have a function func that I want to be executed in a single thread. I want to do this, because I want to test the Single Core Speed of my CPU. I will loop this function(func) for about 20 times, and record the execution time of each repetition, then I will sum the results and get the average execution time.
#include <thread>
int func(long long x)
{
int div = 0;
for(long i = 1; i <= x / 2; i++)
if(x % i == 0)
div++;
return div + 1;
}
int main()
{
std::thread one_thread (func,100000000);
one_thread.join();
return 0;
}
So , in this program, does the func is executed on a single particular core ?
Here is the source code of my program:
#include <iostream>
#include <thread>
#include <iomanip>
#include <windows.h>
#include "font.h"
#include "timer.h"
using namespace std;
#define steps 20
int func(long long x)
{
int div = 0;
for(long i = 1; i <= x / 2; i++)
if(x % i == 0)
div++;
return div + 1;
}
int main()
{
SetFontConsolas(); // Set font consolas
ShowConsoleCursor(false); // Turn off the cursor
timer t;
short int number = 0;
cout << number << "%";
for(int i = 0 ; i < steps ; i++)
{
t.restart(); // start recording
std::thread one_thread (func,100000000);
one_thread.join(); // wait function return
t.stop(); // stop recording
t.record(); // save the time in vector
number += 5;
cout << "\r ";
cout << "\r" << number << "%";
}
double time = 0.0;
for(int i = 0 ; i < steps ; i++)
time += t.times[i]; // sum all recorded times
time /= steps; // get the average execution time
cout << "\nExecution time: " << fixed << setprecision(4) << time << '\n';
double score = 0.0;
score = (1.0 * 100) / time; // calculating benchmark score
cout << "Score: ";
SetColor(12);
cout << setprecision(2) << score << " pts";
SetColor(15);
cout << "\nPress any key to continue.\n";
cin.get();
return 0;
}
No, your program has at least two treads: main, and the one you've created to run func. Moreover, neither of these threads is guaranteed to get executed on particular core. Depending on OS scheduler they may switch cores in unpredictable manner. Though main thread will mostly just wait. If you want to lock thread execution on particular core then you need to set thread core affinity by some platform-specific method such as SetThreadAffinityMask on Windows. But you don't really need to go that deep because there is no core switch sensitive code in your example. There is even no need to spawn separate thread dedicated to perform calculations.
If your program doesn't have multiple threads in the source and if the compiler does not insert automatic parallelization, the program should run on a single core (at a time).
Now depending on your compiler you can use appropriate optimization levels to ensure that it doesn't parallelize.
On the other hand what might happen is that the compiler can completely eliminate the loop in the function if it can statically compute the result. That however doesn't seem to be the issue with your case.
I don't think any C++ compiler makes use of multiple core, behind your back. There would be large language issues in doing that. If you neither spawn threads nor use a parallel library such as MPI, the program should execute on only one core.
Abstract:
I wrote a short program dealing with the Chrono library in C++ for experimentation purposes. I want the CPU to count as high as it can within one second, display what it counted to, then repeat the process within an infinite loop.
Current Code:
#include <iostream>
#include <chrono>
int counter()
{
int num = 0;
auto startTime = std::chrono::system_clock::now();
while (true)
{
num++;
auto currentTime = std::chrono::system_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(currentTime - startTime).count() == 1)
return num;
}
}
int main()
{
while(true)
std::cout << "You've counted to " << counter() << "in one second!";
return 0;
}
Problem:
The conditional statement in my program:
if (std::chrono::duration_cast<std::chrono::seconds>(currentTime - startTime).count() == 1)
isn't being triggered because the casted value of currentTime - startTime never equals nor rises above one. This can be demonstrated by replacing the operator '==' with '<', which outputs an incorrect result, as opposed to outputting nothing at all. I don't understand why the condition isn't being met; if this program is gathering time from the system clock at one point, then repeatedly comparing it to the current time, shouldn't the integer value of the difference equal one at some point?
You're hitting a cout issue, not a chrono issue. The problem is that you're printing with cout which doesn't flush if it doesn't feel like it.
cerr will flush on newline. Change to cerr and add a \n and you'll get what you expect.
std::cerr << "You've counted to " << counter() << "in one second!\n";
For some reason the code I'm about to post below is not purely random... And I have used srand(), to attempt to make it random.. I don't know why it's acting weird...
#include<vector>
#include "../Header Files/SinglePlayer.h"
SinglePlayer::SinglePlayer()
{
}
int myRand(int low, int high)
{
srand(time(NULL));
return rand() % (high - low + 1) + low;
}
void SinglePlayer::startGame()
{
cout << "Starting Single Player........." << endl;
cout << "Starting out with two cards...." << endl;
int randomCardStarterOnePlayer = myRand(0,10);
int randomCardStarterTwoPlayer = myRand(0,10);
int randomCardStarterOneAI = myRand(0,10);
int randomCardStarterTwoAI = myRand(0,10);
this -> calculateRandomStarter(randomCardStarterOnePlayer,
randomCardStarterTwoPlayer,
randomCardStarterOneAI,
randomCardStarterTwoAI);
cout << "You Start out with " << amountPlayer << endl;
cout << "Computer Starts out with " << amountAI << endl;
}
void SinglePlayer::calculateRandomStarter(int randomOnePlayer, int randomTwoPlayer, int randomOneAI, int randomTwoAI)
{
amountPlayer = amountPlayer + randomOnePlayer + randomTwoPlayer;
playerCards.push_back(randomOnePlayer);
playerCards.push_back(randomTwoPlayer);
amountAI = amountAI + randomOneAI + randomTwoAI;
AICards.push_back(randomOneAI);
AICards.push_back(randomTwoAI);
}
SinglePlayer::~SinglePlayer()
{
}
Outcome:
~~~~~~~~~~BLACKJACK~~~~~~~~~~~
Do you want to play single player, or multiplayer? (Enter 0 for single
player, 1 for multiplayer)
0
Starting Single Player.........
Starting out with two cards....
You Start out with 2
Computer Starts out with 2
You can see the player and computer starts with same number.. and that always happens for some reason... I cant seem to spot the problem, please help.
time(NULL) returns time in seconds, and because you set new seed every time you are generating new number you probably (in most cases) set same number as seed every time.
Move:
srand(NULL)
to start of main or somewhere where it will be called only once.
It sounds like time(NULL) in your code returns something that is constant and does not call std::time(NULL) as you may expect. If it did, you would have a random number properly generated from rand().
Try to print the output of time(NULL) and check if you actually get the number of seconds elasped since the epoch. If not, make sure you include <ctime> and call fully qualified srand(std::time(NULL)).
I am trying to write a class that will be able to time events using QueryPerformanceCounter in C++.
The idea is that you create a timer object, give a function a time in double format, and it counts until that time has passed by and does stuff afterwards. This class will ideally be used for timing things in a game ( having a timer that counts 60 times in a second for example). When i compile this code though, it just prints 0's to the console, seemingly for ever. But i noticed some kind of bug that i can't understand. If i click on the scroll bar of the console window and hold it, the timer actually counts properly. If i enter 5.0 for example, then quickly click and hold the scroll bar for 5 seconds or longer, when i let go the program will print 'Done!!!'. so why doesn't it count properly when i just let it print the elapsed time to the console? is there a glitch with printing things to the console, or is there something wrong with my timing code? Below is the code:
#include <iostream>
#include <iomanip>
#include "windows.h"
using namespace std;
int main()
{
setprecision(10); // i tried to see if precision in the stream was the problem but i don't think it is
cout << "hello! lets time something..." << endl;
bool timing = 0; // a switch to turn the timer on and off
LARGE_INTEGER T1, T2; // the timestamps to count
LARGE_INTEGER freq; // the frequency per seccond for measuring the difference between the stamp values
QueryPerformanceFrequency(&freq); // gets the frequency from the computer
// mil.QuadPart = freq.QuadPart / 1000; // not used
double ellapsedtime = 0, desiredtime; // enter a value to count up to in secconds
// if you entered 4.5 for example, then it should wait for 4.5 secconds
cout << "enter the amount of time you would like to wait for in seconds (in double format.)!!" << endl;
cin >> desiredtime;
QueryPerformanceCounter(&T1); // gets the first stamp value
timing = 1; // switches the timer on
while(timing)
{
QueryPerformanceCounter(&T2); // gets another stamp value
ellapsedtime += (T2.QuadPart - T1.QuadPart) / freq.QuadPart; // measures the difference between the two stamp
//values and then divides them by the frequency to get how many secconds has ellapsed
cout << ellapsedtime << endl;
T1.QuadPart = T2.QuadPart; // assigns the value of the second stamp to the first one, so that we can measure the
// difference between them again and again
if(ellapsedtime>=desiredtime) // checks if the elapsed time is bigger than or equal to the desired time,
// and if it is prints done and turns the timer off
{
cout << "done!!!" << endl;
timing = 0; // breaks the loop
}
}
return 0;
}
You should store in ellapsedtime the number of microseconds elapsed since the fisrt call to QueryPerformanceCounter, and you should not overwrite the first time stamp.
Working code:
// gets another stamp value
QueryPerformanceCounter(&T2);
// measures the difference between the two stamp
ellapsedtime += (T2.QuadPart - T1.QuadPart);
cout << "number of tick " << ellapsedtime << endl;
ellapsedtime *= 1000000.;
ellapsedtime /= freq.QuadPart;
cout << "number of Microseconds " << ellapsedtime << endl;
// checks if the elapsed time is bigger than or equal to the desired time
if(ellapsedtime/1000000.>=desiredtime) {
cout << "done!!!" << endl;
timing = 0; // breaks the loop
}
Be sure to read : Acquiring high-resolution time stamps