Measuring the running time of a program using clock() function - c++

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
clock_t t;
t = clock();
for(int i=0;i<1000000;i++)
;
t=clock()-t;
cout<<(float)t/CLOCKS_PER_SEC<<endl;
return 0;
}
I wrote a sample c++ program to measure the running time. Every time I run this code I get a different output. How is this happening? Shouldn't the time required by this program be same every time I run it.

I think that your running time you had is true. In the multitasking operating system, we have multi thread, so when your program running, maybe other program request CPU and your program to be comming delay for it.
You should read:
Easily measure elapsed time
If you are curious about the game timer program. You can use the game loop.
follows this:
How to make timer for a game loop?

Related

Countdown timer in C++?

Is it possible to create a countdown timer in C++ (any ver.),
WHILE we are interacting on the output screen.
for example: A game is being played and we have to stop it after some given time.
I can create the timer either by using clock function or loop, but then, while the timer runs of course, I can't do anything.
So I want something like, a game being played and timer running in background, and the game ends, as the time is over.
There is a quite simple answer to your question...
... multithreading!!!
It allows you to run processes parallel.
Little example:
#include <iostream>
#include <thread>
using namespace std;
void threadfunction(){
//Timer stuff here
}
int main()
{
thread t1(threadfunction);
// your game here
t1.join();
return 0;
}
I haven't tried the code yet because I hadn't the time, but I think it should work.
You could change a global variable if the time is elapsed to stop the game.
Hope this was helpful.

any way to run 2 loops at the same time?

I want to create a c++ program for a bank queue. Where every 3 minutes a new customer enters the queue. every customer needs 5 minutes for the service. The program print out the information after the first 30 minutes
The time of arriving for each customer
The time of leaving for each customer
How many customers are in the line?
Who is the current serving customer?
I wrote the current code:
#include <queue>
#include <ctime>
#include <time.h>
#include <conio.h>
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
queue <int> inq;
queue <int> inservice;
int z= 1;
for(int i=0; i<=9; i++)
{
inq.push(z);
Sleep(180000);
_strtime_s(hold_time);
cout<<"Time of arriving for customer number "<<z<<" is: "<<hold_time<<endl;
z++;
}
do
{
inservice.push(inq.front());
Sleep(300000);
_strtime_s(hold_time);
cout<<"Time of leaving for customer number "<<z<<" is: "<<hold_time<<endl;
inq.pop();
}
while(!inq.empty());
cout<<"number of customers waiting : "<<inq.size()<<endl;
cout<<"Customer number "<<inservice.front()<< " is currently serving"<<endl;
return 0;
}
The current code executes line by line; customers will not be moved to service until the queue loop is done.
To adjust time, I have to run the two loops at the same time. such that customers enter the queue at the same time other costumers are being served
Any suggestions ?
To run two loops at the same time, you will need to put them in different threads. Maybe start here to understand threading.
If you want a simulator of bank queuing, you can consider implementing it in Python using SimPy. A bank queue is even one of the examples:
SimPy Bank Example
You need a more sophisticated code architecture for this. Either naive threading, or an event-dispatch framework that has one busy-loop in main and periodically (based on timers and on events) calls out to other functions as needed.
The most basic yet robust solution you could do would be to have one loop that iterates very quickly (with a very small sleep), repeatedly checking the time to see whether it's time to perform any actions. Those actions will include customers arriving and customers leaving.
Using sleep in other any context is, IMO, usually the sign of a bad design.
A sophisticated way to approach this would indeed use threading, but if you don't want to do that you should instead loop over time, i.e.
for (int minutes = 1; mintues <= 30; minutes++) {
// if minutes modulo 3 do something
// if minutes modulo 5 do something
}
You could loop over seconds, microseconds, whatnot.

How to use boost to track real time instead of user+sys?

I'm using boost::timer to time a section of my code. If I run the code with one thread:
$ time ./runfoo 1
Took 2.08s
real 0m2.086s
user 0m1.611s
sys 0m0.475s
2.08 is the output of t.elapsed().
Yet if I run the code with 4 threads:
$ time ./runfoo 4
Took 2.47s
real 0m1.022s
user 0m1.834s
sys 0m0.628s
It seems to be tracking user+sys time, not real time.
How do I make it track real time? I'm using Boost 1.46. To be more specific, the timer is in the main thread, which just calls a function that ends up using the multiple threads.
EDIT: The relevant source looks something like this:
boost::asio::io_service ios;
boost::thread_group pool;
boost::asio::io_service::work work(ios);
pool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
pool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
pool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
pool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
{
boost::timer t;
function_which_posts_to_ios(ios);
printf("Took %.2fs\n", t.elapsed();
}
As to what output I expect, I'd like the program in the 2nd run to print "Took 1.02s" instead of "Took 2.47s", as 1.02s was the actual amount of seconds that elapsed.
It appears that you are using the deprecated Version 1 timers where the semantics of elapsed() was not consistent across platforms, wall-clock time on some and CPU time on others. In the Version 2 cpu_timer, the elapsed() method returns a struct which has distinct members for real, user, and system time.
If you cannot use the Version 2 API, you can use boost::posix_time instead to measure wall clock time. See c++ boost get current time in milliseconds.

C++: keeping track of elapsed time

I'm looking for a way to be able to know how much time it's been since my program was started, at any given time. A sort of timer that would keep running while the main code is doing everything else, and that can be called at any time.
The context is an OpenGL application on Windows, and as well as knowing which keyboard keys are being pressed (using glutKeyboardFunc), I'd like to know when exactly each key is pressed. All of this info is written into an XML file that will later be used to replay everything the user did. (sort of like the replay functionality in a car racing game, but more simple).
C++ 11:
#include <iostream>
#include <chrono>
auto start = std::chrono::system_clock::now();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
Code taken from en.cppreference.com and simplified.
Old answer:
GetTickCount() in windows.h returns ticks(miliseconds) elapsed.
When your app starts, call this function and store its value, then whenever you need to know elapsed time since your program start, call this method again and subtract its value from start value.
int start = GetTickCount(); // At Program Start
int elapsed = GetTickCount() - start; // This is elapsed time since start of your program
You don't need a timer for this, you save the timestamp at start of the app with time(0). And the you do the same each time you want to measure the time and you can just to init_time - current_time and you'll get the time lapse.

n900 - maemo - timing

I am attempting to save a file every second within +- 100ms (10% error). The problem I am having is that my timing measurement is saying that execution took 1150 ms, but in reality it appears to be 3 or 4 seconds.
What's going on?
If I issue the command, sleep(1), it appears to be very accurate. However, when I measure how long something took, it must be off by quite a bit.
I am using clock() to measure program execution. All of this stuff is within a while loop.
Walter
Your problem is that clock() reports you CPU time used by your process and it is usually different from the "real" time used.
For example following code:
#include <time.h>
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
clock_t scl = clock();
sleep(1);
cout << "CPU clock time " << clock()-scl << endl;
}
gives
time ./a.out
CPU clock time 0
real 0m1.005s
user 0m0.000s
sys 0m0.004s