Hey im trying to count how long the function takes to execute
I am doing it like this:
Timer.cpp
long long int Timer :: clock1()
{
QueryPerformanceCounter((LARGE_INTEGER*)&time1);
return time1;
}
long long int Timer :: clock2()
{
QueryPerformanceCounter((LARGE_INTEGER*)&time2);
return time2;
}
main.cpp
#include "Timer.h" //To allow the use of the timer class.
Timer query;
void print()
{
query.clock1();
//Loop through the elements in the array.
for(int index = 0; index < num_elements; index++)
{
//Print out the array index and the arrays elements.
cout <<"Index: " << index << "\tElement: " << m_array[index]<<endl;
}
//Prints out the number of elements and the size of the array.
cout<< "\nNumber of elements: " << num_elements;
cout<< "\nSize of the array: " << size << "\n";
query.clock2();
cout << "\nTime Taken : " << query.time1 - query.time2;
}
Can anyone tell me if i am doing this correctly?
You are substracting ending time from starting time.
cout << "\nTime Taken : " << query.time1 - query.time2;
should be
cout << "\nTime Taken : " << query.time2 - query.time1
Let's say I start something at 10 seconds and it finishes at 30 seconds. How long did it take? 20 seconds. To get that, we would do 30 - 10; that is, the second time subtract the first time.
So perhaps you want:
cout << "\nTime Taken : " << (query.time2 - query.time1);
Related
So I'm writing a program to count the execution time of a function using clock and I used iomanip to change the output to decimal with 9 zeros.
This is the code that I am using:
#include <time.h>
#include <iomanip>
using namespace std;
void linearFunction(int input)
{
for(int i = 0; i < input; i++)
{
}
}
void execution_time(int input)
{
clock_t start_time, end_time;
start_time = clock();
linearFunction(input);
end_time = clock();
double time_taken = double(end_time - start_time) / double(CLOCKS_PER_SEC);
cout << "Time taken by function for input = " << input << " is : " << fixed
<< time_taken << setprecision(9);
cout << " sec " << endl;
}
int main()
{
execution_time(10000);
execution_time(100000);
execution_time(1000000);
execution_time(10000000);
execution_time(100000000);
execution_time(1000000000);
return 0;
}
And the output shows:
Time taken by function for input = 10000 is : 0.000000 sec
Time taken by function for input = 100000 is : 0.001000000 sec
Time taken by function for input = 1000000 is : 0.002000000 sec
Time taken by function for input = 10000000 is : 0.038000000 sec
Time taken by function for input = 100000000 is : 0.316000000 sec
Time taken by function for input = 1000000000 is : 3.288000000 sec
As you can see, the first time I call the function, it doesn't follow the setprecision(9) that I wrote. Why is this and how can I solve this? Thanks you in advance.
Look at the following line properly:
cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken << setprecision(9);
See? You are setting the precision after printing out time_taken. So for the first time, you don't see the result of setprecision(). But for the second time and onwards, as setprecision() has already been executed, you get the desired decimal places.
So to fix this issue, move setprecision() before time_taken as such:
cout << "Time taken by function for input = " << input << " is : " << fixed << setprecision(9) << time_taken;
..or you can also do something like this:
cout.precision(9);
cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken;
Also, consider not using the following line in your code:
using namespace std;
..as it's considered as a bad practice. Instead use std:: every time like this:
std::cout.precision(9);
std::cout << "Time taken by function for input = " << input << " is : " << std::fixed << time_taken;
For more information on this, look up to why is "using namespace std" considered as a bad practice.
I ran this code for a preliminary benchmark, which compares the time taken to generate a certain number of random states using the scale a double random value and using a Bernoulli distribution. The code is below:
int main()
{
std::random_device s;
std::mt19937 engine(s());
std::bernoulli_distribution bernp50(0.5000000000000000);
std::uniform_real_distribution<double> d;
long int limit = 10000000000; //10^10
int counter[2] = {0};
{
Timer bernstate("Bern Two States");
for(int i = limit; i>0; i--)
{
int tmp = bernp50(engine);
//Implicit bool to int conversion
counter[tmp]++;
}
}
cout << " Bern Two States - 0,1 \n\nCounter:\n" << "0: " <<
counter[0] <<"\n1: " << counter[1]<<"\n"
<< "Counter additions: " << counter[0] + counter[1] << "\n\n"
<< "\n0: " << (double)((double)counter[0]*100/(double)limit) << "%"
<< "\n1: " << (double)((double)counter[1]*100/(double)limit) << "%"
<< "\n\n" << endl;
counter[0]=0;
counter[1]=0;
{
Timer double_comp("Two State - Double");
for(int i = limit; i>0; i--)
{
double temp = d(engine)*2;
if(temp < 1)
{
counter[0]++;
}
else
{
counter[1]++;
}
}
}
cout << " Double Two States - 0,1 \n\nCounter:\n" << "0: " <<
counter[0] <<"\n1: " << counter[1]<<"\n"
<< "Counter additions: " << counter[0] + counter[1] << "\n\n"
<< "\n0: " << (double)((double)counter[0]*100/(double)limit) << "%"
<< "\n1: " << (double)((double)counter[1]*100/(double)limit) << "%"
<< "\n\n" << endl;
} //End of Main()
For limit = 10^10 I get the result, where the counter additions is greater than the limit variable. Same for 10^11:
Timer Object: Bern Two States Timer Object Destroyed: Bern Two States Duration Elapsed: 85.9409 s
Bern Two States - 0,1
Counter: 0: 705044031 1: 705021377 Counter additions: 1410065408
0: 7.05044% 1: 7.05021%
Timer Object: Two State - Double Timer Object Destroyed: Two State - Double Duration Elapsed: 87.6082 s
Double Two States - 0,1
Counter: 0: 705029886 1: 705035522 Counter additions: 1410065408
0: 7.0503% 1: 7.05036%
However, for limit = 10^9, the results are fine:
Timer Object: Bern Two States
Timer Object Destroyed: Bern Two States
Duration Elapsed: 62.5088 s
Bern Two States - 0,1
Counter:
0: 500005067
1: 499994933
Counter additions: 1000000000
0: 50.0005%
1: 49.9995%
Timer Object: Two State - Double
Timer Object Destroyed: Two State - Double
Duration Elapsed: 62.6709 s
Double Two States - 0,1
Counter:
0: 500015398
1: 499984602
Counter additions: 1000000000
0: 50.0015%
1: 49.9985%
Resolved: I actually used long int for the counters as well, but the problem was with the loop range iterator which was a 4-byte integer. The loop was actually messing up.
For this car wash simulation, your program reads in the car arrival time through an input file. The total wash time for a car is 3 minutes. Another car can not go into the wash while a car is being washed which will increase the waiting time. If a car departs at minute 3 the next car needs to go in at minute 4 if it has already arrived.
I have already tried reading in the file all at once and then creating another loop but that has not worked. I have tried many things, I think I am only having a problem with how to loop the program.
#include <iostream>
#include <cassert>
#include <fstream>
#include <queue>
#include <cstdlib>
using namespace std;
class averager {
private:
int cnt;
int sum;
public:
averager(){
cnt=0;
sum=0;
}
void plus_next_number(int value)
{
cnt++;
sum+=value;
}
double average_time()
{
assert(cnt>0);
return (sum/cnt);
}
int how_many_cars()
{
return cnt;
}
};
class Washmachine {
private:
int time_for_wash;
int time_left;
public:
Washmachine(int n) {
time_for_wash = n;
time_left = 0;
}
bool is_busy() {
return (time_left > 0);
}
void startWashing() {
if(!is_busy()) {
time_left = time_for_wash;
}
}
void one_second(){
if(is_busy()) {
--time_left;
}
}
};
int main() {
queue<int> waitQueue;
int carArrival;
averager cal;
ifstream infile;
ofstream arrivalrec;
arrivalrec.open("arrival_time.txt");
arrivalrec << "Car Number " << "Arrival Time " << "Car Wash Start Time " << "Departure Time "
<< "Wait Time "
<< "Total Time " << endl
<< endl;
int maxWaitTime; // maxWaitTime initially 0:00
int totalWaitTime; // total time customers wait
int endTime = 540; // times for the simulation
int totalServiceTime;
int startTime;
int carNum = 0; // number of cars washed in study
int washTime = 3; // fixed time for a wash in minutes
int DeptTime;
int TotalTime;
int timeleft=0;
int waitTime;
int temp;
int sw;
Washmachine carwashing(washTime);
infile.open("input.txt");
for (int startTime=0;startTime<=endTime;startTime++){
infile>>temp;
waitQueue.push(temp);
if((!carwashing.is_busy())&&(!waitQueue.empty())) {
carArrival=waitQueue.front();
waitQueue.pop();
waitTime=temp-carArrival;
cal.plus_next_number(temp-carArrival);
carwashing.startWashing();
}
carwashing.one_second();
if (maxWaitTime<waitTime)
maxWaitTime=waitTime;
// add waiting time for customer to totalWaitTime.
totalWaitTime+=waitTime;
totalServiceTime+=washTime;
startTime=temp+waitTime;
TotalTime=washTime+waitTime;
DeptTime=startTime +washTime;
// increment the number of customers served
carNum++;
// set washAvailable to false since equipment back in service
// output the summary data for the simulation include number of cars
// washed, average customer waiting time and pct of time wash operates
arrivalrec << carNum << " " << temp << " " <<startTime
<< " " << DeptTime << " " <<
waitTime << " " << TotalTime << endl
<< endl << endl;
}
arrivalrec << "Maximum customer waiting time for a car wash is "
<< "14 minutes" << endl;
arrivalrec << "Percentage of time car wash operates is 57 "
//<< ((totalServiceTime / endTime) * 100.0)
<< '%' << endl;
arrivalrec << "Number of customers remaining at " << endTime
<< " is 8"<<endl; //<< waitQueue.size() << endl;
arrivalrec<<"\nCars washed were: "<<carNum<<endl;
arrivalrec<<"\nThe average waiting time is: "<<cal.average_time()<<endl;
int car_denied=0;
while(!waitQueue.empty())
{
waitQueue.pop();
car_denied++;
}
arrivalrec<<"\nThe number of denied cars is: 2 "<<endl;
arrivalrec<<endl;
return 0;
}
Car Arrival 0 car start 0 car depart 3 wait time 0 total time 3
3 4 7 1 4
10 10 13 0 3
11 14 17 3 6
Please try the following loop for the main function of your Car washing simulation.
Instead of looping over startTime, the loop uses the simulation runTime. All events like putting a car to the queue, starting and documenting the car washing process as well as counting waitTime are done by conditions:
infile.open("input.txt");
infile >> temp;
carNum = 1;
for (runTime=1;runTime<=endTime;runTime++){
if (runTime == temp) {
waitQueue.push(temp);
infile >> temp;
}
if((!carwashing.is_busy())&&(!waitQueue.empty())) {
carArrival=waitQueue.front();
waitQueue.pop();
startTime = runTime;
waitTime=startTime-carArrival;
totalWaitTime = waitTime;
TotalTime = washTime + waitTime;
cal.plus_next_number(startTime-carArrival);
carwashing.startWashing();
}
else
{
waitTime++;
}
if (carwashing.is_busy())
carwashing.one_second();
if ((!carwashing.is_busy())&&(startTime >= DeptTime)) {
DeptTime = startTime + washTime;
totalServiceTime += washTime;
arrivalrec << carNum << " " << carArrival << " " << startTime
<< " " << DeptTime << " " <<
totalWaitTime << " " << TotalTime << endl
<< endl << endl;
carNum++;
}
}
Please note that the file reading of the first car is done outside of the loop.
I also added the runTime variable and some initialization to your declaration:
queue<int> waitQueue;
int carArrival = 0;
averager cal;
ifstream infile;
ofstream arrivalrec;
arrivalrec.open("arrival_time.txt");
arrivalrec << "Car Number " << "Arrival Time " << "Car Wash Start Time " << "Departure Time "
<< "Wait Time "
<< "Total Time " << endl
<< endl;
int maxWaitTime = 0; // maxWaitTime initially 0:00
int totalWaitTime = 0; // total time customers wait
int endTime = 75; // times for the simulation
int totalServiceTime = 0;
int startTime = 0;
int carNum = 0; // number of cars washed in study
int washTime = 3; // fixed time for a wash in minutes
int DeptTime = 0;
int TotalTime = 0;
int timeleft=0;
int waitTime=0;
int temp;
int sw;
int runTime;
Washmachine carwashing(washTime);
I've taken the desired output from your other post:
Hope it helps you?
This is FCFS cpu scheduling algorithm.
void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[])
{
// Calculating turnaround time by adding bt[i] + wt[i]
for (int i = 0; i < n; i++)
tat[i] = bt[i] + wt[i];
}
// Function to calculate average waiting and turn-around
// times.
void findavgTime(int processes[], int n, int bt[], int at[])
{
int wt[n], tat[n];
// Function to find waiting time of all processes
findWaitingTime(processes, n, bt, wt, at);
// Function to find turn around time for all processes
findTurnAroundTime(processes, n, bt, wt, tat);
// Display processes along with all details
cout << "Processes " << " Burst Time " << " Arrival Time "
<< " Waiting Time " << " Turn-Around Time "
<< " Completion Time \n";
int total_wt = 0, total_tat = 0;
for (int i = 0; i < n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
int compl_time = tat[i] + at[i];
cout << " " << i + 1 << "\t\t" << bt[i] << "\t\t" << at[i] << "\t\t"
<< wt[i] << "\t\t " << tat[i] << "\t\t " << compl_time << endl;
}
cout << "Average waiting time = " << (float) total_wt / (float) n;
cout << "\nAverage turn around time = " << (float) total_tat / (float) n;
}
How are variables like wt and tat connected if they are decleared inside each function?(This is the main question)
full code is working.
How are variables like wt and tat connected if they are decleared inside each function?
wt and tat are defined in findavgTime. (They are defined using a non-standard extension but that's a separate issue).
When findavgTime calls findWaitingTime and findTurnAroundTime, it passes those variables to the functions. The functions don't define them in their function body -- they are defined in the functions by way of function arguments. Since wt and tat are arrays, they decay to a pointer to the first elements of the respective arrays when findWaitingTime and findTurnAroundTime are called. Because of that, any changes made to the variables inside those functions are visible in findavgTime too.
You don't have to use the same variable names in the function arguments. You could use
void findTurnAroundTime(int processes[], int n, int bt[], int wt_here[], int tat_here[])
{
for (int i = 0; i < n; i++)
tat_here[i] = bt[i] + wt_here[i];
}
That won't change the behavior of the program.
This may be very simple but I am confused!
I am getting segmentation fault when extracting information from a pointer to a pointer. See the cout section in main(). Any help will be appreciated.
Thanks..
Sen
#include <stdlib.h>
#include <iostream>
typedef struct{
int hour;
int minute;
} Time;
Time* GetNextTime(void)
{
Time *p_time = new Time;
return p_time;
}
void GetTime( Time **sometime )
{
int length = 10;
sometime = new Time*[length];
for(int i=0; i<length; i++)
{
sometime[i] = GetNextTime();
sometime[i]->hour = rand()%24 ;
sometime[i]->minute = rand()%60;
std::cout << "Entered times " << sometime[i]->hour << " hour " << sometime[i]->minute << " minutes " << std::endl;
}
}
int main()
{
Time** _time;
GetTime( _time );
//here is the question
// I cant print them from original _time
for( int i=0; i<10; i++)
std::cout << " Print times " << (*_time)[i].hour << " hour " << (*_time)[i].minute << " minutes " << std::endl;
}
You're passing sometime by value, not by reference so it remains uninitialized. Change GetTime to the following:
void GetTime( Time ** &sometime ) //& means pass by reference
Because you're creating an array of pointers, you can use array notation to access them during printing as well.
std::cout << " Print times " << _time[i]->hour << " hour "
<< _time[i]->minute << " minutes " << std::endl;
Unless an argument is explicitly labelled as using a reference it is passed by value in C++. Thus, assigning to sometime in GetTime() has no effect on _time in main().
My strong advice is not to us explict memory allocation but use containers, e.g. std::vector<T>, instead. You'd still need to pass the container by refernence, however.
In main
It should be
Time *_time;
GetTime(&_time)
And then cout should be done with _time instead of *_time