Here is a clear question:
can you provide a simple example of chrono being called from main (or its own class) and used in another class. Or a link to an example.
and below is me fumbling around trying to explain my problem in more detail:
I have been working on this all day and keep ending up in the same place.
I am writing a program that is supposed to output the elapsed time after certain processes finish.
The problem I am having is that these processes are happening in different classes and I cannot get the clock to work properly.
I keep reverting back to having the clock in the main but am really struggling to make everything mesh together. So maybe this is a simple question about working with classes. But there is something about I am not understanding and I don't know what it is.
Below are the 4 lines of this timer that I keep reverting back to and placing in my main function. It prints the clock how I want in the format x.xxxxxx
auto clock_start = chrono::system_clock::now();
auto clock_now = chrono::system_clock::now();
float currentTime = float(chrono::duration_cast <chrono::microseconds> (clock_now - clock_start).count());
cout << "Elapsed Time: " << currentTime /1000000 << " S \n";
Eventually,
I have a queue of structs that im popping in a loop that I then manipulate. They need a time-stamp when printed at the end of each loop iteration.
I just can't for the life of me get the timer to give the time elapsed (or even work) while in the loop.
is this possible? I have read many threads on chrono and something is just not clicking for me when I try using the timer in multiple classes/functions across my program.
EDIT***
SO here is my current class in my meta.h:
These are private members inside class Meta
typedef std::chrono::system_clock timer;
timer::time_point currentTime;
timer::time_point startTime;
timer::time_point clock_wait;
timer::time_point clock_check;
timer::time_point elapsed_time; // this is my issue
And then I start the time in meta.cpp
void Meta::startTimer()
{
startTime = timer::now();
}
And here is the loop with some pieces missing so we can focus on the timer:
void Meta::displaySim()
{
//auto clock_start = chrono::system_clock::now(); THIS IS WHAT I WAS DOING
queue<sData>newFile;
while (!MetaQ.empty())
{
temp = MetaQ.front();
bool wait = true;
float waitTime = float(temp.ncycle)/1000;
while (wait)
{
clock_wait = timer::now();
clock_check = timer::now();
elapsed_time = timer::duration_cast<chrono::milliseconds>(clock_check - clock_wait);
if (elapsed_time.count() > waitTime)
wait = false;
}
cout << "****" << waitTime << "*****"<< endl;
end_time = timer::now();
//Below is the line that is giving me trouble now. I get an error when casting. I don't know how to make duration_cast part of the timer declared in meta.h
float EndTime = float(timer::duration_cast <chrono::milliseconds>(end_time - startTime).count());
cout << fixed << EndTime / 1000000 << " - (" << temp.desc << ')' << temp.cycle << " - " << temp.ncycle << " ms\n";
newFile.push(temp);
MetaQ.pop();
}
MetaQ = newFile;
}
timer::time_point elapsed_time; // this is my issue
Just from the name elapsed_time, this doesn't sound like a time_point. It sounds like a duration. Do this to fix that problem:
timer::duration elapsed_time;
This looks suspicious:
float waitTime = float(temp.ncycle)/1000;
Typically a time duration should have type std::chrono::duration<some representation, some period>. And you don't want to apply conversion factors like 1/1000 manually. Let <chrono> handle all conversions.
elapsed_time = timer::duration_cast<chrono::milliseconds>(clock_check - clock_wait);
duration_cast is not a static member function of system_clock. duration_cast is a namespace scope function. Use it like this:
elapsed_time = chrono::duration_cast<chrono::milliseconds>(clock_check - clock_wait);
If waitTime had a duration type, the .count() would be unnecessary here:
if (elapsed_time.count() > waitTime)
// Below is the line that is giving me trouble now. I get an error when casting.
// I don't know how to make duration_cast part of the timer declared in meta.h
float EndTime = float(timer::duration_cast <chrono::milliseconds>(end_time - startTime).count());
Best practice is to stay within the <chrono> type system instead of escaping to scalars such as float. You can get integral milliseconds with this:
auto EndTime = chrono::duration_cast<chrono::milliseconds>(end_time - startTime);
If you really want EndTime to be float-based milliseconds, that is easy too:
using fmilliseconds = chrono::duration<float, std::milli>;
fmilliseconds EndTime = end_time - startTime;
For more details, here is a video tutorial for the <chrono> library: https://www.youtube.com/watch?v=P32hvk8b13M
If this answer doesn't address your question, distill your problem down into a complete minimal program that others can copy/paste into their compiler and try out. For example I could not give you concrete advice on waitTime because I have no idea what temp.ncycle is.
Finally, and this is optional, if you would like an easier way to stream out durations for debugging purposes, consider using my free, open source, header-only date/time library. It can be used like this:
#include "date/date.h"
#include <iostream>
#include <thread>
using timer = std::chrono::system_clock;
timer::time_point clock_wait;
timer::time_point clock_check;
timer::duration elapsed_time;
int
main()
{
using namespace std::chrono_literals;
clock_wait = timer::now();
std::this_thread::sleep_for(25ms); // simulate work
clock_check = timer::now();
elapsed_time = clock_check - clock_wait;
using date::operator<<; // Needed to find the correct operator<<
std::cout << elapsed_time << '\n'; // then just stream it
}
which just output for me:
25729µs
The compile-time units of the duration are automatically appended to the run-time value to make it easier to see what you have. This prevents you from accidentally appending the wrong units to your output.
Related
I'm currently making a small game for my C++ programming class and the professor requires us to have a timer for the game. We haven't talked at all about how to use timers and any std timer libraries so we're on our own. I found the std library and have tried to implement a simple timer for the game and have managed to do so but I can't seem to figure out how to format the time from it to a more user friendly version like HH:MM:SS.Millisecons. All I have is the raw time since I started the steady_clock till I ended it and I can display that in seconds, milliseconds, minutes, whatever, but that doesn't look as good as I'd like to. I found some solutioms but they are way too hard for me to even deconstruct and try to apply. Any simple way to do what I want?
Part of my code where I implement the timer:
// Initialize game timer using <chrono>
chrono::steady_clock::time_point start = chrono::steady_clock::now();
// While game is running (player alive and enemy robot lefts) update map
while (!GameEnd){
show_maze(maze_map);
cout << endl;
playerMove(x, y, GameEnd, died, maze_map);
}
// Terminate game timer and calculate time elapsed
chrono::steady_clock::time_point end = chrono::steady_clock::now();
chrono::steady_clock::duration time_elapsed = end - start;
// Show last map state before either player died or no more robots left
show_maze(maze_map);
// Boo / congratulate player for his performance on the game
cout << "Game Over! You " << (died ? "died by hitting a fence/robot :(" : "won because all the robots died. Congratulations!") << endl;
cout << "Your game lasted for " << chrono::duration_cast<chrono::milliseconds>(time_elapsed).count() << " milliseconds.\n\n";
You can get the number of hours out of time_elapsed with:
auto h = chrono::duration_cast<chrono::hours>(time_elapsed);
Then you can subtract the number of hours so that time_elapsed only holds a duration less than an hour:
time_elapsed -= h;
Then you can get the number of minutes out of time_elapsed:
auto m = chrono::duration_cast<chrono::minutes>(time_elapsed);
and subtract the minutes out...
time_elapsed -= m;
Now time_elapsed holds a duration less than a minute. You can continue with this pattern down to whatever granularity you desire.
C++20 has a type called std::chrono::hh_mm_ss that does precisely this operation as a convenience:
chrono::hh_mm_ss hms{time_elapsed};
hh_mm_ss has hours(), minutes(), seconds() and subseconds() getters which return the respective chrono units. To the best of my knowledge, no vendor is shipping this yet, but you can get a preview of this part of C++20, which works with C++11/14/17 here.
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
chrono::steady_clock::time_point start = chrono::steady_clock::now();
// ...
chrono::steady_clock::time_point end = chrono::steady_clock::now();
chrono::steady_clock::duration time_elapsed = end - start;
cout << date::hh_mm_ss{chrono::duration_cast<chrono::milliseconds>(time_elapsed)} << '\n';
}
Output:
00:00:00.000
I've got timer issue in GLUT.
glutGet(GLUT_ELAPSED_TIME) only get time with sec accuracy (1000, 2000, 3000...)
and
glutTimerFunc(...) works only when millis parameter is set greater than 1000.
I don't know exactly how GLUT measure time
but I think there's something wrong with my system time setting.
How can I get time with millis accuracy in OpenGL?
As already mentioned in the comments above, you could use more reliable C++ date and time utilities like the std::chrono library. Here is a simple example:
#include <iostream>
#include <chrono>
int main()
{
const auto start = std::chrono::high_resolution_clock::now();
// do something...
const auto end = std::chrono::high_resolution_clock::now();
std::cout << "Took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms\n";
return 0;
}
I want to measure the time of a child process
#include <time.h>
int main() {
...
time t begin, end, diff;
...
//fork etc in here
time(&begin);
...
//some things
...
time(&end);
return 0;
}
I have 2 Time stamps now, is there a way to format it to the run-time of the child process to hours:minutes:seconds?
I have tried
diff = end - begin;
But I get a huge number then.
(Sorry for only a part of the code but it's on another PC.)
You can compute the difference with difftime:
double diff_in_seconds = difftime(end, begin);
or, for better precision, use one of C++11 chrono monotonic clocks such as std::steady_clock:
auto start = std::chrono::steady_clock::now();
// some things
auto end = std::chrono::steady_clock::now();
double time_in_seconds = std::chrono::duration_cast<double>(end - start).count();
See also this answer for details why you should use a monotonic clock.
You should probably compute the difference using difftime instead of subtraction, in case your system uses some other format for time_t besides "integer number of seconds".
difftime returns the number of seconds between the two times, as a double. It's then a simple matter of arithmetic to convert to hours, minutes and seconds.
The attempt in the question is a C way, not C++. In C++11 (assuming you have one), you can get 2 time points and then cast the difference between them to the units you need, as in the example here: http://en.cppreference.com/w/cpp/chrono/duration/duration_cast
Nearly copying the code:
auto t1 = std::chrono::high_resolution_clock::now();
// Call your child process here
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "Child process took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()
<< " milliseconds\n";
My goal is to calculate the performance of my thread by seeing how long it took to run but I am getting some issues:
My code is as follows:
#include
thread() {
struct timeval start, finish;
gettimeofday(&start, NULL);
-- code --
gettimeofday(&start, NULL);
double dif = ((end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)*0.000001);
printf("%f", dif);
}
I want my code to print in the format of seconds and miliseconds like: 3.252 or something similar but I get something like: 0.1615680.161717.
Does anyone know how to convert this format to the standard x.xxxx seconds version?
C++11's chrono library makes this easy. How easy? This easy:
Required include:
#include <chrono>
Thread body:
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
start = std::chrono::high_resolution_clock::now();
//--code--
end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end-start;
std::cout << elapsed.count() << std::endl;
Links to libraries and functions used:
chrono
high_resolution_clock
duration
And as an added bonus, it works on more than just Linux.
To print a double: printf("%lf", dif);
Edit (correction): It doesn't matter if the specifier is %f or %lf, the argument gets promoted to double.
Also you are using inconsistently the variables. Both calls to gettimeofday are using start variable. Where is end used?
What is the simplest and cleanest way to get the time since execution of the program (with milliseconds precision) in C++ ?
I am making a wave interference simulator to produce Lissajous curves in C++. It requires the time since execution of the program (with at least milliseconds precision) to function. I can't seem to find any clean and simple way to do it after a bit of research.
All <chrono> functions seem very confusing to me. Similar questions on here on Stack Overflow seem to be either unrelated, confusing (to me) or inapplicable for my situation. I tried using functions from <time.h>, only to discover that they have precision upto seconds only.
I am running Windows 7 x64. The program need not be platform independent as it's for personal use.
Any help is greatly appreciated.
Thank you!
The new <chrono> functions take a little getting used to but they make things fairly easy when you get to know how they work.
Your problem could be solved like this for example:
#include <chrono>
#include <thread>
#include <iostream>
// for readability
using hr_clock = std::chrono::high_resolution_clock;
using hr_time_point = hr_clock::time_point;
using hr_duration = hr_clock::duration;
using milliseconds = std::chrono::milliseconds;
int main()
{
// note the program start time
hr_time_point prog_start = hr_clock::now();
// do stuff
std::this_thread::sleep_for(milliseconds(1000));
// find the duration
hr_duration d = hr_clock::now() - prog_start;
// cast the duration to milliseconds
milliseconds ms = std::chrono::duration_cast<milliseconds>(d);
// print out the number of milliseconds
std::cout << "time passed: " << ms.count() << " milliseconds.\n";
}
For convenience you could create a function to return the time since that function was last called:
milliseconds since_last_call()
{
// retain time between calls (static)
static hr_time_point previous = hr_clock::now();
// get current time
hr_time_point current = hr_clock::now();
// get the time difference between now and previous call to the function
milliseconds ms = std::chrono::duration_cast<milliseconds>(current - previous);
// store current time for next call
previous = current;
// return elapsed time in milliseconds
return ms;
}
int main()
{
since_last_call(); // initialize functions internal static time_point
// do stuff
std::this_thread::sleep_for(milliseconds(1000));
milliseconds ms = since_last_call();
// print out the number of milliseconds
std::cout << "time passed: " << ms.count() << " milliseconds.\n";
}