Cleanest and simplest way to get elapsed time since execution in C++ - c++

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";
}

Related

Process Timing Discrepancies

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();
}

Stopwatch class in c++

I have to write a stopwatch class in c++. The way I am trying to do this is by defining a variable to save laps (named 'time') and a bool that I use to see if the watch is started or stopped. When entering a char the timer should start and set time1. When another char is entered the bool switches to false and sets time2 and then prints time2-time1. This should be repeatable until 'n' is entered
I also am not quite sure I understand what unit of time time_t is in. In my code i get a return value of ±40 units every time i try to measure the interval of a lap, which I am guessing is the runtime of the program and not actually the time of the interval.
#ifndef stoppuhr_hpp
#define stoppuhr_hpp
#include <iostream>
#include <time.h>
class Stoppuhr{
private:
bool running;
clock_t time;
public:
void pushButtonStartStop () {
char t=0;
running=false;
time=0;
std::cout << "to start/stop watch please press a key, to end
clock type 'n' " << std::endl;
clock_t time1=0;
clock_t time2=0;
std::cout << time;
while (t!='n') {
std::cin >> t;
running= !running;
if (running) {
time1=clock();
}
else {
time2=clock();
time+=time2-time1;
std::cout << time << std::endl;
}
}
}
};
#endif /* stoppuhr_hpp */
I also am not quite sure I understand what unit of time time_t is in.
The unit of time represented by time_t is implementation specified. Usually, it represents seconds, as specified by POSIX.
However, you don't use time_t anywhere in your program.
I am guessing is the runtime of the program
I recommend not to guess, but to read documentation instead. clock() returns the processor time used by the program since some point in time. So deducting two timepoints returned by clock() will give you the processor time used between those timepoints. The unit of clock_t is 1 / CLOCKS_PER_SEC seconds.
i get a return value of ±40 units every time
Granularity of clock is implementation specified. It might be 40 units on your system. The program consumes hardly any processor time while it waits for input.
I have to write a stopwatch class
Stopwatches typically measure real world time i.e. wall clock time. Measuring processor time would be futile for this task.
I recommend using std::chrono::steady_clock::now instead.
If you insist on using time.h, then you can use time(nullptr) to get the wall clock time but I don't recommend it.

How to get the time elapsed running a function in C++

I tried some codes by googling :
clock_t start, end;
start = clock();
//CODES GOES HERE
end = clock();
std::cout << end - start <<"\n";
std::cout << (double) (end-start)/ CLOCKS_PER_SEC;
but the result elapsed time always was 0, even with
std::cout << (double) (end-start)/ (CLOCKS_PER_SEC/1000.0 );
Don't know why but when I get the similar in Java : getCurrentTimeMillis() it works well. I want it to show the milliseconds as maybe the computer compute so fast.
I don't think it's guaranteed that clock has a high enough resolution to profile your function. If you want to know how fast a function executes, you should run it maybe a few thousands times instead of once, measure the total time it takes and take the average.
#include <boost/progress.hpp>
int main()
{
boost::progress_timer timer;
// code to time goes here
}
This will print out the time it took to run main. You can place your code in scopes to time several parts, i.e. { boost::progress_timer timer; ... }.
This question is somehow similar to yours: Timing a function in a C++ program that runs on Linux
Take a look at this answer!

c++ get milliseconds since some date

I need some way in c++ to keep track of the number of milliseconds since program execution. And I need the precision to be in milliseconds. (In my googling, I've found lots of folks that said to include time.h and then multiply the output of time() by 1000 ... this won't work.)
clock has been suggested a number of times. This has two problems. First of all, it often doesn't have a resolution even close to a millisecond (10-20 ms is probably more common). Second, some implementations of it (e.g., Unix and similar) return CPU time, while others (E.g., Windows) return wall time.
You haven't really said whether you want wall time or CPU time, which makes it hard to give a really good answer. On Windows, you could use GetProcessTimes. That will give you the kernel and user CPU times directly. It will also tell you when the process was created, so if you want milliseconds of wall time since process creation, you can subtract the process creation time from the current time (GetSystemTime). QueryPerformanceCounter has also been mentioned. This has a few oddities of its own -- for example, in some implementations it retrieves time from the CPUs cycle counter, so its frequency varies when/if the CPU speed changes. Other implementations read from the motherboard's 1.024 MHz timer, which does not vary with the CPU speed (and the conditions under which each are used aren't entirely obvious).
On Unix, you can use GetTimeOfDay to just get the wall time with (at least the possibility of) relatively high precision. If you want time for a process, you can use times or getrusage (the latter is newer and gives more complete information that may also be more precise).
Bottom line: as I said in my comment, there's no way to get what you want portably. Since you haven't said whether you want CPU time or wall time, even for a specific system, there's not one right answer. The one you've "accepted" (clock()) has the virtue of being available on essentially any system, but what it returns also varies just about the most widely.
See std::clock()
Include time.h, and then use the clock() function. It returns the number of clock ticks elapsed since the program was launched. Just divide it by "CLOCKS_PER_SEC" to obtain the number of seconds, you can then multiply by 1000 to obtain the number of milliseconds.
Some cross platform solution. This code was used for some kind of benchmarking:
#ifdef WIN32
LARGE_INTEGER g_llFrequency = {0};
BOOL g_bQueryResult = QueryPerformanceFrequency(&g_llFrequency);
#endif
//...
long long osQueryPerfomance()
{
#ifdef WIN32
LARGE_INTEGER llPerf = {0};
QueryPerformanceCounter(&llPerf);
return llPerf.QuadPart * 1000ll / ( g_llFrequency.QuadPart / 1000ll);
#else
struct timeval stTimeVal;
gettimeofday(&stTimeVal, NULL);
return stTimeVal.tv_sec * 1000000ll + stTimeVal.tv_usec;
#endif
}
The most portable way is using the clock function.It usually reports the time that your program has been using the processor, or an approximation thereof. Note however the following:
The resolution is not very good for GNU systems. That's really a pity.
Take care of casting everything to double before doing divisions and assignations.
The counter is held as a 32 bit number in GNU 32 bits, which can be pretty annoying for long-running programs.
There are alternatives using "wall time" which give better resolution, both in Windows and Linux. But as the libc manual states: If you're trying to optimize your program or measure its efficiency, it's very useful to know how much processor time it uses. For that, calendar time and elapsed times are useless because a process may spend time waiting for I/O or for other processes to use the CPU.
Here is a C++0x solution and an example why clock() might not do what you think it does.
#include <chrono>
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
auto start1 = std::chrono::monotonic_clock::now();
auto start2 = std::clock();
sleep(1);
for( int i=0; i<100000000; ++i);
auto end1 = std::chrono::monotonic_clock::now();
auto end2 = std::clock();
auto delta1 = end1-start1;
auto delta2 = end2-start2;
std::cout << "chrono: " << std::chrono::duration_cast<std::chrono::duration<float>>(delta1).count() << std::endl;
std::cout << "clock: " << static_cast<float>(delta2)/CLOCKS_PER_SEC << std::endl;
}
On my system this outputs:
chrono: 1.36839
clock: 0.36
You'll notice the clock() method is missing a second. An astute observer might also notice that clock() looks to have less resolution. On my system it's ticking by in 12 millisecond increments, terrible resolution.
If you are unable or unwilling to use C++0x, take a look at Boost.DateTime's ptime microsec_clock::universal_time().
This isn't C++ specific (nor portable), but you can do:
SYSTEMTIME systemDT;
In Windows.
From there, you can access each member of the systemDT struct.
You can record the time when the program started and compare the current time to the recorded time (systemDT versus systemDTtemp, for instance).
To refresh, you can call GetLocalTime(&systemDT);
To access each member, you would do systemDT.wHour, systemDT.wMinute, systemDT.wMilliseconds.
To get more information on SYSTEMTIME.
Do you want wall clock time, CPU time, or some other measurement? Also, what platform is this? There is no universally portable way to get more precision than time() and clock() give you, but...
on most Unix systems, you can use gettimeofday() and/or clock_gettime(), which give at least microsecond precision and access to a variety of timers;
I'm not nearly as familiar with Windows, but one of these functions probably does what you want.
You can try this code (get from StockFish chess engine source code (GPL)):
#include <iostream>
#include <stdio>
#if !defined(_WIN32) && !defined(_WIN64) // Linux - Unix
# include <sys/time.h>
typedef timeval sys_time_t;
inline void system_time(sys_time_t* t) {
gettimeofday(t, NULL);
}
inline long long time_to_msec(const sys_time_t& t) {
return t.tv_sec * 1000LL + t.tv_usec / 1000;
}
#else // Windows and MinGW
# include <sys/timeb.h>
typedef _timeb sys_time_t;
inline void system_time(sys_time_t* t) { _ftime(t); }
inline long long time_to_msec(const sys_time_t& t) {
return t.time * 1000LL + t.millitm;
}
#endif
struct Time {
void restart() { system_time(&t); }
uint64_t msec() const { return time_to_msec(t); }
long long elapsed() const {
return long long(current_time().msec() - time_to_msec(t));
}
static Time current_time() { Time t; t.restart(); return t; }
private:
sys_time_t t;
};
int main() {
sys_time_t t;
system_time(&t);
long long currentTimeMs = time_to_msec(t);
std::cout << "currentTimeMs:" << currentTimeMs << std::endl;
Time time = Time::current_time();
for (int i = 0; i < 1000000; i++) {
//Do something
}
long long e = time.elapsed();
std::cout << "time elapsed:" << e << std::endl;
getchar(); // wait for keyboard input
}

How to get system time in C++?

In fact i am trying to calculate the time a function takes to complete in my program.
So i am using the logic to get system time when i call the function and time when the function returns a value then by subtracting the values i get time it took to complete.
So if anyone can tell me some better approach or just how to get system time at an instance it would be quite a help
The approach I use when timing my code is the time() function. It returns a single numeric value to you representing the epoch which makes the subtraction part easier for calculation.
Relevant code:
#include <time.h>
#include <iostream>
int main (int argc, char *argv[]) {
int startTime, endTime, totalTime;
startTime = time(NULL);
/* relevant code to benchmark in here */
endTime = time(NULL);
totalTime = endTime - startTime;
std::cout << "Runtime: " << totalTime << " seconds.";
return 0;
}
Keep in mind this is user time. For CPU, time see Ben's reply.
Your question is totally dependant on WHICH system you are using. Each system has its own functions for getting the current time. For finding out how long the system has been running, you'd want to access one of the "high resolution performance counters". If you don't use a performance counter, you are usually limited to microsecond accuracy (or worse) which is almost useless in profiling the speed of a function.
In Windows, you can access the counter via the 'QueryPerformanceCounter()' function. This returns an arbitrary number that is different on each processor. To find out how many ticks in the counter == 1 second, call 'QueryPerformanceFrequency()'.
If you're coding under a platform other than windows, just google performance counter and the system you are coding under, and it should tell you how you can access the counter.
Edit (clarification)
This is c++, just include windows.h and import the "Kernel32.lib" (seems to have removed my hyperlink, check out the documentation at: http://msdn.microsoft.com/en-us/library/ms644904.aspx). For C#, you can use the "System.Diagnostics.PerformanceCounter" class.
You can use time_t
Under Linux, try gettimeofday() for microsecond resolution, or clock_gettime() for nanosecond resolution.
(Of course the actual clock may have a coarser resolution.)
In some system you don't have access to the time.h header. Therefore, you can use the following code snippet to find out how long does it take for your program to run, with the accuracy of seconds.
void function()
{
time_t currentTime;
time(&currentTime);
int startTime = currentTime;
/* Your program starts from here */
time(&currentTime);
int timeElapsed = currentTime - startTime;
cout<<"It took "<<timeElapsed<<" seconds to run the program"<<endl;
}
You can use the solution with std::chrono described here: Getting an accurate execution time in C++ (micro seconds) you will have much better accuracy in your measurement. Usually we measure code execution in the round of the milliseconds (ms) or even microseconds (us).
#include <chrono>
#include <iostream>
...
[YOUR METHOD/FUNCTION STARTING HERE]
auto start = std::chrono::high_resolution_clock::now();
[YOUR TEST CODE HERE]
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
std::cout << "Elapsed time: " << microseconds << " ms;