Let me start by saying, I am not a skilled C++ programmer, I have just begun that journey and am working in a Win 10 environment using Code::Blocks as my ide. I am starting to learn C++ by coding solutions to the Euler Project problems. I used these problems to start learning Python several years ago, so I have at least one Python solution for the first 50+ problems. In doing these problems in Python, I learned that as my skill improves, I can formulate better solutions. When learning Python, I used a trial & error approach to improving my code until I became aware of the python tools for timing my code. Once, I defined a convenient and consistent timing method, my coding improved dramatically. Since, I am beginning this journey now with C++ I decided I would be proactive and create a consistent method for timing the code execution. To do this, I have decided to utilize the C++ chrono library and have defined two different approaches that seemingly should produce the same time results. However as the tile to this question implies they don't.
So here's my question: Why don't the following two approaches yield the same results?
Approach # 1
This method provides a timing for the do some stuff segment of slightly over 3 seconds, but less than the CODE::BLOCKS execution time report of 3.054 seconds. I certainly understand these differences based on the program flow. So this approach seems to give good result. The issue I have with this approach is I need to copy & paste the timing code into each .cpp file I want to time, which seems sloppy.
Output using this method looks like the following:
Elapsed time in seconds : 3.00053 sec
Process returned 0 (0x0) execution time : 3.151 s
#include <iostream>
#include <chrono>
#include <unistd.h>
using namespace std;
using Clock = chrono::steady_clock;
using TimePoint = chrono::time_point<Clock>;
// Functions
TimePoint get_timestamp();
double get_duration(TimePoint, TimePoint);
int main()
{
//auto start = chrono::steady_clock::now();
auto start_t = get_timestamp();
//cout << "Start is of type " << typeid(start).name() << "\n";
// do some stuff
sleep(3);
auto end_t = get_timestamp();
//double tme_secs = chrono::duration_cast<chrono::nanoseconds>(end - start).count()/1000000000.0000;
double tme_secs = get_duration(start_t, end_t)/1000000000;
cout << "Elapsed time in seconds : " << tme_secs << " sec";
return 0;
}
TimePoint get_timestamp(){
return Clock::now();
}
double get_duration(TimePoint start, TimePoint end){
return chrono::duration_cast<chrono::nanoseconds>(end - start).count()*1.00000000;
}
Approach #2
In this approach, I attempted to create a ProcessTime class which could be included in files that I want to time and provide a cleaner method. The problem with this approach is I get timing report in the nano seconds, which does not reflect the process being timed. Here is my implementation of this approach.
output using this method looks like the following:
Elapsed time: 1.1422e+06 seconds
Process returned 0 (0x0) execution time : 3.148 s
ProcessTime.h file
#ifndef PROCESSTIME_H_INCLUDED
#define PROCESSTIME_H_INCLUDED
#include <chrono>
using namespace std;
using Clock = chrono::steady_clock;
using TimePoint = chrono::time_point<Clock>;
class ProcessTime{
public:
ProcessTime();
double get_duration();
private:
TimePoint proc_start;
};
#endif // PROCESSTIME_H_INCLUDED
ProcessTime.cpp file
#include "ProcessTime.h"
#include <chrono>
using namespace std;
using Clock = chrono::steady_clock;
using TimePoint = chrono::time_point<Clock>;
ProcessTime::ProcessTime(){
TimePoint proc_start = Clock::now();
}
double ProcessTime::get_duration(){
TimePoint proc_end = Clock::now();
return chrono::duration_cast<chrono::nanoseconds>(proc_end - ProcessTime::proc_start).count()*1.00000000;
}
main.cpp file:
#include <iostream>
#include "ProcessTime.h"
#include <unistd.h>
using namespace std;
int main()
{
ProcessTime timer;
// Do some Stuff
sleep(3);
double tme_secs = timer.get_duration()/1000000000;
cout << "Elapsed time: " << tme_secs << " seconds";
return 0;
}
This is incorrect:
ProcessTime::ProcessTime(){
TimePoint proc_start = Clock::now();
}
You are setting a local variable named proc_start, and then the constructor ends. You did not set the actual member variable of ProcessTime.
One fix (and the preferred method) is to use the member-initialization list:
ProcessTime::ProcessTime() : proc_start(Clock::now()) {}
or if you knew nothing about the member-initialization list, the code would look like this to assign the value.
ProcessTime::ProcessTime(){
proc_start = Clock::now();
}
Related
I need to measured elapsed time in ms
I need to store the start time as a primitive type
I need to retrieve the start time as a primitive type, when making the comparison to determine how much time has elapsed
Any suggestions?
I have C++17 and do not want to use any external libraries (like boost).
std::chrono would be fine if someone could explain to me how to convert the elapsed time to/from a primitive. I'm not very good at C++.
resolution accuracy is not important.. if it is off by tens of ms that's ok, I just need to implement a delay.. e.g. 100ms or 1.5s
Because you are storing the start time, you should use std::chrono::system_clock. Its epoch is stable, and will not change with time. Other std::chrono clocks have an epoch that may change between runs of a program, and thus time points stored by one run and read back in by a subsequent run may not be consistent.
To get the current time in milliseconds:
auto now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
I like to use either a using directive or a namespace alias to make such code less verbose:
using namespace std::chrono;
auto now = time_point_cast<milliseconds>(system_clock::now());
To convert now into a signed 64 bit integral type:
auto now_i = now.time_since_epoch().count();
To convert now_i back into a time_point:
time_point<system_clock, milliseconds> prev{milliseconds{now_i}};
To compare time_points:
if (now > prev)
...
Everything above is in the header <chrono>:
#include <chrono>
You can simply do this by:
double time = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC;
See the below code for better understanding.
#include <iostream>
#include <time.h>
using namespace std;
int main() {
double start = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC;
for(int i=0;i<1e9;i++);
double end = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC;
double time_taken = end - start;
cout << time_taken << "ms\n";
return 0;
}
Include the header file:
#include <time.h> // include this
I am trying to use a while loop to create a timer that consistently measures out 3000μs (3 ms) and while it works most of the time, other times the timer can be late by as much as 500μs. Why does this happen and is there a more precise way to make a timer like this?
int getTime() {
chrono::microseconds μs = chrono::duration_cast< chrono::microseconds >(
chrono::system_clock::now().time_since_epoch() //Get time since last epoch in μs
);
return μs.count(); //Return as integer
}
int main()
{
int target = 3000, difference = 0;
while (true) {
int start = getTime(), time = start;
while ((time-start) < target) {
time = getTime();
}
difference = time - start;
if (difference - target > 1) { //If the timer wasn't accurate to within 1μs
cout << "Timer missed the mark by " + to_string(difference - target) + " microseconds" << endl; //Log the delay
}
}
return 0;
}
I would expect this code to log delays that are consistently within 5 or so μs, but the console output looks like this.
Edit to clarify: I'm running on Windows 10 Enterprise Build 16299, but the behavior persists on a Debian virtual machine.
You need to also take into account other running processes. The operating system is likely preempting your process to give CPU time to those other processes/threads, and will non-deterministically return control to your process/thread running this timer.
Granted, this is not 100% true when we consider real-time operating systems or flat-schedulers. But this is likely the case in your code if you're running on a general purpose machine.
Since you are running on Windows, that RTOS is responsible for keeping time through NTP, as C++ has no built-in functions for it. Check out this Windows API for the SetTimer() function: http://msdn.microsoft.com/en-us/library/ms644906(v=vs.85).aspx.
If you want the best and most high-resolution clock through C++, check out the chrono library:
#include <iostream>
#include <chrono>
#include "chrono_io"
int main()
{
typedef std::chrono::high_resolution_clock Clock;
auto t1 = Clock::now();
auto t2 = Clock::now();
std::cout << t2-t1 << '\n';
}
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.
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";
}
I am writing a program that will be used on a Solaris machine. I need a way of keeping track of how many seconds has passed since the start of the program. I'm talking very simple here. For example I would have an int seconds = 0; but how would I go about updating the seconds variable as each second passes?
It seems that some of the various time functions that I've looked at only work on Windows machines, so I'm just not sure.
Any suggestions would be appreciated.
Thanks for your time.
A very simple method:
#include <time.h>
time_t start = time(0);
double seconds_since_start = difftime( time(0), start);
The main drawback to this is that you have to poll for the updates. You'll need platform support or some other lib/framework to do this on an event basis.
Use std::chrono.
#include <chrono>
#include <iostream>
int main(int argc, char *argv[])
{
auto start_time = std::chrono::high_resolution_clock::now();
auto current_time = std::chrono::high_resolution_clock::now();
std::cout << "Program has been running for " << std::chrono::duration_cast<std::chrono::seconds>(current_time - start_time).count() << " seconds" << std::endl;
return 0;
}
If you only need a resolution of seconds, then std::steady_clock should be sufficient.
You are approaching it backwards. Instead of having a variable you have to worry about updating every second, just initialize a variable on program start with the current time, and then whenever you need to know how many seconds have elapsed, you subtract the now current time from that initial time. Much less overhead that way, and no need to nurse some timing related variable update.
#include <stdio.h>
#include <time.h>
#include <windows.h>
using namespace std;
void wait ( int seconds );
int main ()
{
time_t start, end;
double diff;
time (&start); //useful call
for (int i=0;i<10;i++) //this loop is useless, just to pass some time.
{
printf ("%s\n", ctime(&start));
wait(1);
}
time (&end);//useful call
diff = difftime(end,start);//this will give you time spent between those two calls.
printf("difference in seconds=%f",diff); //convert secs as u like
system("pause");
return 0;
}
void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
this should work fine on solaris/unix also, just remove win refs
You just need to store the date/time when application started. Whenever you need to display for how long your program is running get current date/time and subtract the when application started.