Different output when using cout + printf vs printf only - c++

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?

Related

Measuring running time of program with clock

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.

How do I add modulus to this? (hours:minutes:seconds)

This is my first time on this site, and as such, the format of this question may be wrong in some ways. That being said, here is the exercise I am struggling with.
"Write a C++ program that prompts the user to input the elapsed time for an event in seconds. The program then outputs the elapsed time in hours, minutes, and seconds. (For example, if the elapsed time is 9630 seconds, then the output is 2:40:30.)"
Here is what I have programmed so far in Code::Blocks-
#include <iostream>
#include <string>
using namespace std;
int main()
{
int seconds;
int hours;
int minutes;
int seconds1;
cout << "How long did the event take in seconds?" << endl;
cin >> seconds;
hours= seconds/3600;
minutes= %(seconds/3600);
seconds1= %(seconds/minutes);
cout << "The event took"<<hours<<":"<<minutes<<":"<<seconds1<<"." << endl;
cout << endl;
return 0;
}
My main question is how I would add the modulus operation to this program. I know I need to include it, as there is a clear remainder after variable: hour, and minute.
Also, two error codes appear when this program is run through the compiler:
Line 16) error: expected primary-expression before '%' token
Line 17) error: expected primary-expression before '%' token
minutes= %(seconds/3600);
the syntax for the mod, % operator in an assignment is
minutes = value1 % value2;
You have no left-hand argument, here value1, in your expression.
The seconds1 part is straightforward, you just take the seconds mod 60.
seconds1 = seconds % 60;
The minutes part you'll have to think about a little. You can do it in two ways.
You need to subtract the number of seconds already accounted for by the hours value, then divide by 60. No mod required, or rather a manual mod.
using mod. Get the remainder of the hours not accounted for by the hours calculation, % 3600 then calculate the number of minutes this is.

Error multiplying numbers in the trillions

I am trying to perform a calculation to get from the total microseconds of the current time back to the current time in HHMMSSFFF format by performing a series of calculations. However, when I try to subtract the hours*3600000000 from the total number of microseconds, the returned value is not correct (it is off by one order of magnitude and the number itself is wrong. Does anyone know how to fix this? I tried using long long int and long double but these both outputted the same value. I have copied below the code and the resulting output in the console.
The times are stored in a vector as data comes in (aka a time stamp) which is why there is a temp_counter. I am using time_duration in the boost::posix_time library.
long double total = cur_time.at(temp_counter).total_microseconds();
cout << total << endl;
int hours = total/(3600000000);
cout << hours << endl;
long long int temp = hours*3600000000;
cout << std::setprecision(20) << temp << endl;
total = total - temp;
cout << total << endl;
Output:
35465976558
9
2335228928
33130747630
By my calculations, temp should actually be 32400000000 and the new total should be 3065976558.
The calculation is:
35465976558/
3600000000 = 9,851660155 cast to int equals 9
9 * 3600000000 = ... and here the crap hits the fan because 3600000000 cannot be put into a 32 bit int and doesn't seem to be cast correctly to long long, hence you should cast the right hand side to long long int.
But as you are getting a long double in the first assignment: Why not using long double (or at least double) all the way and avoid the casting horror?

Job scheduling c++ simulation, need advice/suggestion

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

C++ clock() function giving incorrect values

I was trying to program a Timer class (unaware that boost had one), then when that wasn't working, I tried to just output the value of clock(), using this code:
#include <ctime>
#include <iostream>
int main()
{
for(int i = 0; i < 50; ++i)
{
std::cout << std::clock() << " ";
}
return 0;
}
When I run the program, I get a series of 0s. I have a similar experience when using boost thread sleep functions to spread out timing a little longer (although after a few seconds, it jumps from 0 to 10,000 and keeps outputting 10,000).
I'm running Gentoo Linux. Is this a platform thing? A C++ thing? What's going on?
Edit: Strangely the jump to 10000 comes after a number of seconds, not milliseconds. When I was sleeping my thread for a second at a time, it took five or six seconds to get to 10000. However, if I'm understanding correctly. The time the thread spends sleeping doesn't contribute towards the clock() count? (Which would make sense; why would it be executing clock cycles if it's sleeping?)
The clock() return value is specified in microseconds. But typical granularity of whatever low-level system call the clock() implementation uses is much lower. So it seems that on your system the granularity is 10ms. Also note that clock() does NOT measure real time - it measures CPU time used by the program. So the time flows when your program controls the CPU, and it freezes when your program is suspended - sleeping, for example.
std::clock's resolution is unspecified. In most cases, it's resolution is going to be about 10ms. Hence the jump.
Try the following:
#include <ctime>
#include <iostream>
int main()
{
for(int i = 0; i < 50; ++i)
{
for (int j = 0; j < 500; ++j )
{
std::cout << j << " ";
}
std::cout << std::endl;
std::cout << std::clock() << std::endl;
}
std::cout << std::endl;
return 0;
}
On my system, I see the return value of clock() staying at 0 until at some point it jumps to 10000. It stays at 10000 till the end. If I remove the std::cout in the inner loop, the return value of clock() stays at 0 all the way through. Looks like clock() returns values in increments of 10000 only.
If I change the inner loop to compute the square root of j and print the return value of sqrt(), the return value of clock() goes up to 50000, but is still increases in increments of 10000.
on my 64 bit operating system the CLOCKS_PER_SEC speed is 1000.and the values of clock comes in milliseconds. perfect timing will be extracted from the code below.
int main(){
clock_t a,b;
int c,d,e,f;
c=clock();
scanf("%d",&e);
d=clock();
f=(d-c)/CLOCKS_PER_SECOND;
printf("timing is %d seconds",f);/*for 64 bit operating system
CLOCKS_PER_SECOND is 1000*/
}