Measure the time taken by the program - c++

I have the .exe of a program which has been generated from C++.
Is there some simple snippet which I could just insert to get the time taken by the program. I have the C++ code available but I don't want to tweak it much.

Read about Boost.Timers. Code sample to measure time will be:
#include <boost/timer/timer.hpp>
boost::timer t0;
// do smth
std::cout<<"elapsed: "<< t0.elapsed() << " s\n";

A simple way to measure the time taken by some part (or all) of your program is to take a snapshot of the current time at the start and then subtract it from the current time at the end. On Windows, you could use the GetTickCount function for this. I commonly wrap this in a little helper struct:
struct Duration {
Duration( const char *name )
: m_start( ::GetTickCount() ),
m_name( name )
{ }
~Duration() {
std::cout << m_name << " executed in " << ::GetTickCount() - start << "ms" << std::endl;
}
const DWORD m_start;
const std::string m_name;
};
You can use it like this:
int main()
{
Duration d( "Program" );
// Heavy work being done here
}
A little timing information is printed to stdout as the Duration object is destroyed.

On unix you would just need to prefix the executable command with "time", and if you by chance have Cygwin installed, then that's what I what suggest to use. Otherwise check Performance Counters, which is the very source of the process performance data on MS platform. It should be possible to do the trick with a pain of one extra method call before the app exit.

Related

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.

Cleanest and simplest way to get elapsed time since execution in 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";
}

C++: How Can I keep my program (output console) alive

I am writing a simple program (my 1st program) to display the laptop battery, however, I would like to keep it active to monitor the battery %.:
using namespace std;
int main(int argc, char *argv[]) {
id:
SYSTEM_POWER_STATUS spsPwr;
if (GetSystemPowerStatus(&spsPwr)) {
cout << "\nAC Status : " << static_cast<double>(spsPwr.ACLineStatus)
<< "\nBattery Status : " << static_cast<double>(spsPwr.BatteryFlag)
<< "\nBattery Life % : " << static_cast<double>(spsPwr.BatteryLifePercent)
<< endl;
system("CLS");
goto id;
return 0;
}
else return 1;
}
using goto seems to be a bad idea as the CPU utilization jump to 99% ! :(, I am sure this is not the right way to do it.
Any suggestion?
Thanks
while (true) {
// do the stuff
::Sleep(2000); // suspend thread to 2 sec
}
(you are on Windows according to the API function)
see: Sleep
First of all, the issue you are asking about: of course you get 100% CPU usage, since you're asking the computer to try and get and print the power status of the computer as fast it possibly can. And since computers will happily do what you tell them to, well... you know what happens next.
As others have said, the solution is to use an API that will instruct your application to go to sleep. In Windows, which appears to be your platform of choice, that API is Sleep:
// Sleep for around 1000 milliseconds - it may be slightly more since Windows
// is not a hard real-time operating system.
Sleep(1000);
Second, please do not use goto. There are looping constructs in C and you should use them. I'm not fundamentally opposed to goto (in fact, in my kernel-driver programming days I used it quite frequently) but I am opposed to seeing it used when better alternatives are available. In this case the better alternative is a while loop.
Before I show you that let me point out another issue: DO NOT USE THE system function.
Why? The system function executes the command passed to it; on Windows it happens to execute inside the context of the command interpreter (cmd.exe) which supports and internal command called cls which happens to clear the screen. At least on your system. But yours isn't the only system in the world. On some other system, there might be a program called cls.exe which would get executed instead, and who knows what that would do? It could clear the screen, or it could format the hard drive. So please, don't use the system function. It's almost always the wrong thing to do. If you find yourself looking for that command stop and think about what you're doing and whether you need to do it.
So, you may ask, how do I clear the screen if I can't use system("cls")? There's a way to do it which should be portable across various operating systems:
int main(int, char **)
{
SYSTEM_POWER_STATUS spsPwr;
while (GetSystemPowerStatus(&spsPwr))
{
std::string status = "unknown";
if (spsPwr.ACLineStatus == 0)
status = "offline";
else if (spsPwr.ACLineStatus == 1)
status = "online";
// The percent of battery life left is returned as a value
// between 0 and 255 so we normalize it by multiplying it
// by 100.0 and dividing by 255.0 which is ~0.39.
std::cout << "Current Status: " << status << " ("
<< static_cast<int>(spsPwr.BatteryFlag) << "): "
<< 0.39 * static_cast<int>(spsPwr.BatteryLifePercent)
<< "% of battery remaining.\r" << std::flush;
// Sleep for around 1000 milliseconds - it may be slightly more
// since Windows is not a hard real-time operating system.
Sleep(1000);
}
// Print a new line before exiting.
std::cout << std::endl;
return 0;
}
What this does is print the information in a single line, then move back to the beginning of that line, sleep for around one second and then write the next line, overwriting what was previously there.
If the new line you write is shorter than the previous line, you may see some visual artifacts. Removing them should not be difficult but I'll leave it for you as an exercise. Here's a hint: what happens if you output a space where a letter used to be?
In order to do this across lines, you will need to use more advanced techniques to manipulate the console, and this exercise becomes a lot trickier.
You are having 100% CPU usage because your program is always running.
I don't want to get into details, and given that this is your first program, I'll recommend to put a call to usleep before the goto.
And, of course, avoid goto, use a proper loop instead.
int milliseconds2wait = 3000;
while (!flag_exit) {
// code
usleep( 1000 * milliseconds2wait )
}
Update: This is windows, use Sleep instead of usleep:
Sleep( milliseconds2wait );

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!

Get time of execution piece of code

How do I get milliseconds time of execution of a piece of code in Qt/C++?
Use the QTime class. Start it with .start() (or .restart()) and then check the amount of milliseconds passed with .elapsed(). Naturally, the precision ultimately depends on the underlying OS, although with the major platforms you should have no trouble getting a real millisecond resolution.
If you are running on a Windows system, then you can use timer based on the Windows Performace Timers and get microsecond timing.
Intel has a downloadable library at etimer libary. This is a small C routine that is fairly painless to use and gives very good results at the microsecond level
If you don't use Qt you can do it with a GetTickCount:
DWORD start = ::GetTickCount(); // start counter
// all the things your program does
DWORD end = ::GetTickCount(); // stop counter
DWORD duration = end - start;
std::cout << "Duration: " << duration << " ms" << std::endl;