I have started creating a c++ program to simulate job scheduling algorithms like FiFo and others. I am far from done but my main problem now is how to create the flow of time in my program.
This is my main code so far:
for (i = 1; i < 10; i++)
{
Time1 = clock();
//this is the alogrithm to generate poisson arrival sequence
do{
k = k + 1;
// Generate a random number between 0 and 1
// return a uniform number in [0,1].
double u = rand() / (double)RAND_MAX;
p = p * u;
}while (p > L);
A[i] = k-1;
Time2 = clock();
DT = Time2 -Time1;
TotalTime=TotalTime + DT;
cout << " Total time " << TotalTime
<< " table :" << A[i]
<< " Arrival Time "
<< TotalTime <<endl ;
My main problem is :
my time measuring units with clock are that the time units that are outputted from clock() function are "weird" numbers. Should I use another function?
Results from 10 iteration
Total time 6.19522e+032 table :28 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :29 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :30 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :31 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :32 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :33 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :34 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :35 Arrival Time 6.19522e+032
Total time 6.19522e+032 table :36 Arrival Time 6.19522e+032
PS: I can provide the rest of the code if you want to run it in your machine.
Job scheduling would be much, much easier to do as a "discrete-event" simulation. Check out this tutorial paper to see how such models can be constructed. The framework in the paper is in Java (and has also been implemented in Ruby), but would be straight-up to port to C++.
So the first point is that clock() returns a clock_t variable so, although I don't think it will really make much of a different, make Time1 and Time2 be of type clock_t. As for the main question and from the comments, looks like you just forgot to initialize TotalTime to zero, which would explain the huge numbers.
If the output is all zero then yes the loop probably is running very quickly but you can also increase the number of decimal places you output by using setprecision. Run the following code to see the difference, cout.setprecision(int value) will determine how many decimal places to show.
#include <iostream>
int main() {
double d = 1.0/3.0;
std::cout.precision(15);
std::cout << d << std::endl;
std::cout.precision(3);
std::cout << d;
return 0;
}
Related
I'm using the below code to calculate the time for execution. It works well when I take input from ./a.out < input.txt. But when I manually write my input it also includes that time. Is there a way to exclude the time taken by the user to input?
auto begin = chrono::high_resolution_clock::now();
// my code here has cin for input
auto end = chrono::high_resolution_clock::now();
cout << chrono::duration_cast<chrono::duration<double>>(end - begin).count() << " seconds";
Edit: I know that we can count the time before cin and after then subtract it. Is there any other way?
A straightforward approach would be to "Freeze time" when user input is required, so instead of creating the end variable after the input lines, create it before the input lines and restart time calculation again after the input:
double total = 0;
auto begin = chrono::high_resolution_clock::now();
// code that needs time calculation
auto end = chrono::high_resolution_clock::now();
total += chrono::duration_cast<chrono::duration<double>>(end - begin).count();
// your code here that has cin for input
begin = chrono::high_resolution_clock::now();
// code that needs time calculation
end = chrono::high_resolution_clock::now();
total += chrono::duration_cast<chrono::duration<double>>(end - begin).count();
cout << total << " seconds";
We are studying the performance of various sorting algorithms and implemented our version of mergesort. We are trying to measure the running time with different input, but when we run the main() program shown below, we are getting different time results.
For example, clock() function output below can show 30 seconds with large input, but when we use the actual timer using our phones, the main program takes about 2 minutes.
What are we missing here? Are we not using the clock() function in a right way? Why is there such a big difference (1.5 minutes)?
Thank you
int n;
cout << "Enter n - lenght of array" << endl;
cin >> n;
vector<int> v(n);
for(int i = 0; i < n; ++i)
{
v[i] = i;
}
auto rng = default_random_engine {};
std::shuffle(std::begin(v), std::end(v), rng);
clock_t begin = clock();
sort(v);
cout << "done";
clock_t end = clock();
cout <<"total time : " << (double)(end-begin) / CLOCKS_PER_SEC<<endl;
return 0;
I ran your code by replacing the sort function with the std::sort, for n=5000000 it showed 11.744s then I moved the line clock_t begin = clock(); before the declaration of vector v and the time was 13.818s
So it seems memory allocation, O(N) initialization and shuffling can take a good amount of time and if you choose a much bigger number for n, depending on the efficiency of your sort function for a random inputset, initialization can take more time than the sort.
I have a program that can generate a random integer every 1/10 second.
Here is the code:
int main()
{
ofstream myfile;
int max;
cout << "Max number: ";
cin >> max;
for (int i = 0; i < max; ++i)
{
myfile.open("test.txt",fstream::app);
myfile << random_int() << "\n";
myfile.close();
this_thread::sleep_for(chrono::milliseconds(100));
}
return 0;
}
int random_int()
{
return rand() % 10;
}
Now the question is, I need to write a program that calculate then output the average in the same rate. If the output of the number generator is:
1
2
3
4
5
The output of the average calculator should be
1
1
2
2
3
Every 1/10 second the program will output a number.
Note: The max number could be from 0 to couple millions. Calculating the average by adding all previous number during the time interval won't be ideal.
I am a sophomore student and a research assistant in a university. This is a simplified version of a problem that I encounter currently. Any suggestion will be greatly appreciated.
Update: Thanks for the help from Fei Xiang and oklar. Yes, remember the previous sum is the only way to make the calculation in time. However, since the random generator output file is changing constantly and the new output is appended to the old outputs, I am not sure how to get the most current data efficiently.
You don't need to calculate all the numbers that has been added each time, you only need to add the last one to a sum variable and divide by the amount of generated numbers.
Say you have:
1
2
3
4
5
Sum variable is 15. If you divide by the amount of numbers which is 5, you'll get the expected output of 3. Continuing, add the number 9 for instance to the sum variable and divide by the amount of generated numbers 6, you'll end up with an average of 4.
The i in your for loop can be used as a counter for the amount of generated numbers. Pseudo code:
sum += randomInt();
avg = sum/i;
EDIT:
I see that you are opening and closing the file each time in the for loop in your post. This can be done outside the loop, which will speed things up. If I understand you correctly, your mission is to generate a random number then calculate the average from the previous numbers and finally append it to the text file? If so, you're on point.
int i_random;
int avg;
int sum = 0;
myfile.open("avg.txt",fstream::app);
for (int i = 1; i < max + 1; ++i)
{
i_random = random_int();
sum += i_random;
avg = sum/i;
myfile << avg << "\n";
this_thread::sleep_for(chrono::milliseconds(100));
}
myfile.close();
See http://www.cplusplus.com/doc/tutorial/files/ for other operators. Check out cppreference for seek and tell if you want to skip to a position in the file.
I am studying C++ in order to make a game and I was able to generate a random number every second using the functions of srand. But I wanted the number to be different every 2 second instead.
Say t is the current time in seconds (time(0)). It is obvious that t changes once per second. Then t/2, because of rounding, changes every two seconds.
Here is a simple way to fix the code.
Put a clock() in an infinite while loop and let the clock count so that when it reaches two seconds, it triggers rand() to generate a new random number. Reset the clock(). Repeat infinitely.
Now the Math behind:
As you already know, delta time is the final time, minus the original time.
dt = t - t0
This delta time, though, is simply the amount of time that passes while in the while loop.
The derivative of a function represents an infinitesimal change in the function with respect to one of its variables. Our deltaTime.
The derivative of a function with respect to the variable is defined as http://mathworld.wolfram.com/Derivative.html
f(x + h) - f(x)
f'(x) = lim -----------------
h->0 h
First you get a time, i.e TimeZero = clock() , for reference.
Then you subtract that time from a new time you just got and devide it by h. h is CLOCKS_PER_SEC. Now delta time is
deltaTime = (clock() - TimeZero) / CLOCKS_PER_SEC;
And when deltaTime > secondsToDelay, you generate a new random number.
Putting all that into code results in this:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
cout << "Generate a new random number every 2 seconds \n\n";
// create a clock and start timer
clock_t TimeZero = clock(); //Start timer
double deltaTime = 0;
double secondsToDelay = 2;
bool exit = false;
// generate random seed using time
srand(time(0));
while(!exit) {
// get delta time in seconds
deltaTime = (clock() - TimeZero) / CLOCKS_PER_SEC;
cout << "\b" << secondsToDelay - deltaTime << "\b";
// compare if delta time is 2 or more seconds
if(deltaTime > secondsToDelay){
cout << " ";
// generate new random number
int i = rand() % 100 + 1;
cout << "\nNew random : " << i << " \n";
//reset the clock timers
deltaTime = clock();
TimeZero = clock();
}
}
return 0;
}
When I'm trying to print a division of a long long integer casted to a float, I get different output when trying to:
use printf().
use std::cout first before printf().
I'm using the long long variable as a sum to a 1000 performance timer results and then average them. I could probably do some recursion average splitting. But I'll worry that later.
Anyways, here's what is happening.
If I do this:
long long sum;
while (j < 1000){
sum += time_record[j];
j++;
}
cout << "Average execution time: "<< sum/1000000 << "ms\n";
printf("Average execution time: %f ms\n", (float)sum/1000000);
the output I get is:
Average execution time: 4ms
Average execution time: 4.197688 ms
Now if I try to remove cout, I get this output:
Average execution time: 140736480.000000 ms
What exactly is happening here?