Get elapsed time just seconds in c++ - c++

I need to get the elapsed time from a while.
something.start()
auto start = std::chrono::steadyt_clock::now();
while(something->is_valid())
{
// getting frames
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
// do something with the frames
if(diff % 3 == 0) { /* do something with the something */ }
}
But it get the time in every ms i get the time and my if statement runs too much. I can not use std::this_thread::sleep_for() cause i need every frame to catch. How can i do it pararell?

Since C++14 you could do diff >= 3s to see if the difference was equal or bigger than three seconds (see this duration literal reference).
Otherwise if you're stuck with C++11 then use diff >= std::chrono::seconds(3).
Note that this requires you to reset start each time the condition is true:
if (diff >= 3s)
{
start = end;
// Do something with the something...
}
This is required because the difference could stay equal to 3 (and therefore diff % 3s == 0 being true) for up to a whole second, which means your "Do something..." part will execute many times falsely.

Related

How to get accurate <1seconds measurements utilizing std::chrono [duplicate]

This question already has answers here:
Measuring execution time of a function in C++
(14 answers)
Getting an accurate execution time in C++ (micro seconds)
(4 answers)
Closed 2 months ago.
I'm trying to compute the amount of time an algorithm runs in my program, and display that amount in differents meausures such as seconds, miliseconds, microseconds...
This is how I've been approaching it:
auto start = high_resolution_clock::now();
myFunction();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(stop - start);
const auto hrs = duration_cast<hours>(duration);
const auto mins = duration_cast<minutes>(duration - hrs);
const auto secs = duration_cast<seconds>(duration - hrs - mins);
const auto ms = duration_cast<milliseconds>(duration - hrs - mins - secs);
std::cout << "Time needed: "<<hrs.count()<<" hours "<<mins.count()<<" mins "<<secs.count()<<" secs " <<ms.count()<<" milisecs "
What I intend it to do (invented example):
Time needed: 0 hours 1 mins 30 seconds 2400miliseconds
BUt for some reasons it prints all 0s (even miliseconds) when times are <1secs, and when times are 1secs or more, it does not prints the exact time either, it does something like
Time needed: 0 hours 0 mins 1 seconds 1000miliseconds
it just print a whole seconds and then it converts it to the others meausures, but the actual time that I took the function to works is not exactly 1 second, how can I get that? (if theres better ways to do that other than std::chrono I'll be interested too)

How to order or compare two circular variables (i.e. milliseconds in whole minute), modular arithmetic [duplicate]

This question already has answers here:
Check if cyclic (modulo 16) number is larger than another?
(4 answers)
Closed 2 years ago.
I have 2 timestamps represented as milliseconds in the last minute. Imagine there are no synchronization issues between nodes.
The receiver has to distinguish which is the first that was generated message. Unfortunately, after 59 seconds the variables restart, then how to compare these two variables?
Remark: imagine there is a max delay between the timers, i.e. 10 seconds. Otherwise the is no solution to this problem.
My solution is posted below.
Comments in code below:
#include <limits.h>
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
bool millis_in_last_minute_is_valid(int time) {
// represented as milliseconds in the last minute
// after 59 seconds the variables restart
static_assert(INT_MAX > 59999, "Use long and not int to represent numbers greater then 2^16. int has __at least__ 16 bits, it may have 16 bits, in which case INT_MAX is around 32000, which will be lower then 59999 and not able to represent your timestamp");
return 0 <= time && time <= 59999;
}
/**
* #return true if time1 is happened before time2, false otherwise.
*/
bool timestamp_millis_in_last_minute_happened_before(int time1, int time2) {
assert(millis_in_last_minute_is_valid(time1));
assert(millis_in_last_minute_is_valid(time2));
const int diff = abs(time2 - time1);
// imagine there is a max delay between the timers, i.e. 10 seconds
/**
There are 4 cases:
0---------time---------->60000
[---------T1--T2-------->
[---------T2--T1-------->
[-T2-----------------T1->
[-T1-----------------T2->
If the difference is smaller then 10 seconds, it's
one of two first cases, if it's grater then 10 seconds,
it's one of the latter. If the latter, the comparison
needs to just be inverted.
*/
// assert the difference between timestamps is max 10 seconds
assert(
// First two cases
(0 <= diff && diff <= 10000) ||
// Latter two cases
(50000 <= diff && diff < 60000));
return diff <= 10000 ? time1 < time2 : time2 < time1;
}
int main() {
// simple test cases with assert
// 0 is not lower then 0 |T1T2-------> T1 happened with T2
assert(timestamp_millis_in_last_minute_happened_before(0, 0) == 0);
// 1 is not lower then 0 |T2-T1------> T1 happened after T2
assert(timestamp_millis_in_last_minute_happened_before(1, 0) == 0);
// 0 is lower then 1 |T1-T2------> T1 happened before T2
assert(timestamp_millis_in_last_minute_happened_before(0, 1) == 1);
// 59 second happens before 1 |T2------T1-> T1 happened before T2
assert(timestamp_millis_in_last_minute_happened_before(59000, 1) == 1);
// 1 happens before 59 second |T1------T2-> T1 happened before T2
assert(timestamp_millis_in_last_minute_happened_before(1, 59000) == 0);
}
Here is my solution:
int compare_timestamp_millis_in_last_minute(int time1, int time2)
{
if(time1 == time2) return 0;
int millisInLastMinute = get_time_in_millis() % MAXMILLISINMINUTE;
if((time1 - millisInLastMinute % MAXMILLISINMINUTE) > (time2 - millisInLastMinute % MAXMILLISINMINUTE))
return 1;
else
return -1;
}
with MAXMILLISINMINUTE = 65535
Idea behind solution: time1 and time 2 are always less than the time at the moment of comparation. Then subtracting a time that is after will move the time1 and time 2 variable in the left quadrant (both less or equal to 59 s).
Anyone has a different solution?

Program That Prints Every (n) Seconds

I wrote a program that for every five seconds would print a random number (1-10) within a ten seconds timeframe. But it seems to be printing more than one random number every five seconds. Could anyone point me in the right direction?
clock_t start;
int random;
start = clock();
while (float(clock() - start) / CLOCKS_PER_SEC <= 10.0) {
if (fmod(float(clock() - start) / CLOCKS_PER_SEC, 5) == 0 && (float(clock() - start) / CLOCKS_PER_SEC) != 0) {
random = rand() % 10 + 1;
cout << random << endl;
}
}
return 0;
EDIT: I felt this answer was incomplete, because it does not answer your actual question. The first part now explains why your approach fails, the second part is about how to solve your problem in a better way.
You are using clock() in a way, where you wait for a number of specific points in time. Due to the nature of clock() and the limited precision of float, your check basically is equivalent to saying: Are we in a window [x-eps, x+eps], where x is a multiple of 5 and eps is generally small and depends on the floating point type used and how big (clock() - start) is. A way to increase eps is to add a constant like 1e6 to (clock() - start). If floating point numbers were precise, that should not affect your logic, because 1e6 is a multiple of 5, but in fact it will do so drastically.
On a fast machine, that condition can be true multiple times every 5 seconds; on a slow machine it may not be true every time 5 seconds passed.
The correct way to implement it is below; but if you wanted to do it using a polling approach (like you do currently), you would have to increment start by 5 * CLOCKS_PER_SECOND in your if-block and change the condition to something like (clock() - start) / CLOCKS_PER_SECOND >= 5.
Apart from the clock()-specific issues that you have, I want to remind you that it measures CPU time or ticks and is hardly a reliable way to measure wall time. Fortunately, in modern C++, we have std::chrono:
auto t = std::chrono::steady_clock::now();
auto end = t + std::chrono::seconds( 10 );
while( t < end )
{
t += std::chrono::seconds( 5 );
std::this_thread::sleep_until( t );
std::cout << ( rand() % 10 + 1 ) << std::endl;
}
I also highly recommend replacing rand() with the more modern tools in <random>, e.g.:
std::random_device rd; // Hopefully a good source of entropy; used for seeding.
std::default_random_engine gen( rd() ); // Faster pseudo-random source.
std::uniform_int_distribution<> dist( 1, 10 ); // Specify the kind of random stuff that you want.
int random = dist( gen ); // equivalent to rand() % 10 + 1.
Your code seems to be fast enough and your calculation precision small enough that you do multiple iterations before the number you are calculating changes. Thus, when the condition matches, it will match several times at once.
However, this is not a good way to do this, as you are making your computer work very hard. This way of waiting will put a rather severe load on one processor, potentially slowing down your computer, and definitely draining more power. If you're on a quad-core desktop it is not that bad, but for a laptop it's hell on batteries. Instead of asking your computer "is it time yet? is it time yet? is it time yet?" as fast as you can, trust that your computer knows how to wait, and use sleep, usleep, sleep_for, or whatever the library you're using is calling it now. See here for an example.

Filter strange C++ multimap values

I have this multimap in my code:
multimap<long, Note> noteList;
// notes are added with this method. measureNumber is minimum `1` and doesn't go very high
void Track::addNote(Note &note) {
long key = note.measureNumber * 1000000 + note.startTime;
this->noteList.insert(make_pair(key, note));
}
I'm encountering problems when I try to read the notes from the last measure. In this case the song has only 8 measures and it's measure number 8 that causes problems. If I go up to 16 measures it's measure 16 that causes the problem and so on.
// (when adding notes I use as key the measureNumber * 1000000. This searches for notes within the same measure)
for(noteIT = trackIT->noteList.lower_bound(this->curMsr * 1000000); noteIT->first < (this->curMsr + 1) * 1000000; noteIT++){
if(this->curMsr == 8){
cout << "_______________________________________________________" << endl;
cout << "ID:" << noteIT->first << endl;
noteIT->second.toString();
int blah = 0;
}
// code left out here that processes the notes
}
I have only added one note to the 8th measure and yet this is the result I'm getting in console:
_______________________________________________________
ID:8000001
note toString()
Duration: 8
Start Time: 1
Frequency: 880
_______________________________________________________
ID:1
note toString()
Duration: 112103488
Start Time: 44
Frequency: 0
_______________________________________________________
ID:8000001
note toString()
Duration: 8
Start Time: 1
Frequency: 880
_______________________________________________________
ID:1
note toString()
Duration: 112103488
Start Time: 44
Frequency: 0
This keeps repeating. The first result is a correct note which I've added myself but I have no idea where the note with ID: 1 is coming from.
Any ideas how to avoid this? This loop gets stuck repeating the same two results and I can't get out of it. Even if there are several notes within measure 8 (so that means several values within the multimap that start with 8xxxxxx it only repeats the first note and the non-existand one.
You aren't checking for the end of your loop correctly. Specifically there is no guarantee that noteIT does not equal trackIT->noteList.end(). Try this instead
for (noteIT = trackIT->noteList.lower_bound(this->curMsr * 1000000);
noteIT != trackIT->noteList.end() &&
noteIT->first < (this->curMsr + 1) * 1000000;
++noteIT)
{
For the look of it, it might be better to use some call to upper_bound as the limit of your loop. That would handle the end case automatically.

Timing a function in microseconds

Hey guys I'm trying to time some search functions I wrote in microseconds, and it needs to take long enough to get it to show 2 significant digits. I wrote this code to time my search function but it seems to go too fast. I always end up getting 0 microseconds unless I run the search 5 times then I get 1,000,000 microseconds. I'm wondering if I did my math wrong to get the time in micro seconds, or if there's some kind of formatting function I can use to force it to display two sig figs?
clock_t start = clock();
index = sequentialSearch.Sequential(TO_SEARCH);
index = sequentialSearch.Sequential(TO_SEARCH);
clock_t stop = clock();
cout << "number found at index " << index << endl;
int time = (stop - start)/CLOCKS_PER_SEC;
time = time * SEC_TO_MICRO;
cout << "time to search = " << time<< endl;
You are using integer division on this line:
int time = (stop - start)/CLOCKS_PER_SEC;
I suggest using a double or float type, and you'll likely need to cast the components of the division.
Use QueryPerformanceCounter and QueryPerformanceFrequency, assuming your on windows platform
here a link to ms KB How To Use QueryPerformanceCounter to Time Code