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*/
}
Related
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.
Before I start, here is the code:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
int i = 0;
while (true) {
i++;
cout << i << endl;
clock_t time = clock() + 1000;
while (clock() != time);
}
return 0;
}
So, basically, it works, however, after a little while it just stops counting down but the program is still running. I'm new to C++ programming and I don't know how to fix this. Could somebody help me out?
EDIT: I'm not wondering how to fix my program still running, I'm wondering how to fix it not outputting numbers at one point randomly.
while (clock() != time);
If you overshoot time, which is very likely given how quickly clock() increments, you'll be stuck in that loop forever.
Use <= instead, so that any greater value of clock() will break the loop.
As an aside, busy-waiting is so 1970. You should prefer a "timed wait" of some kind that blocks until a duration has elapsed.
I would like to make a very basic progress indicator by printing an 'X' char to cout every time a loop progresses another 10%. I am trying to do this as shown in the code pasted below, but it doesn't seem to be working - when really it seems it should.
It's supposed to display steady progress throughout the loop, but instead I get all the X's coming at once after the loop has finished. This is not because the loops are completed too quickly for me to perceive. To verify this you can add an extra 'F' to "TOTAL" to increase the duration of the looping substantially, and you'll see it's not just a question of perception.
Any ideas what might be causing this?
#include <iostream>
#define TOTAL 0xFFFFFFF
using namespace std;
int main(void) {
//Make a counter for counting loops
double counter = 0;
// Set it to trigger after each 10% of progress
double counterMax = TOTAL / 10;
cout << "Starting now..." << endl;
for (double i = 0; i < TOTAL; i++) {
// Do something... anything
i++;
i--;
// Increment the counter
counter++;
// Print an X when the counter exceeds the 10%
// trigger point, and then reset the counter.
if (counter > counterMax) {
cout << 'X';
counter = 0;
}
}
cout << endl << "Done!";
return 0;
}
System input/output calls are usually slow operations. To increase the efficiency of programs, input and output streams are often buffered, to reduce the number of calls to the operating system.
When a program needs "non-buffered" output, one solution is to use the buffered output functions, and simple "flush" the output to ensure the operating system processes any output which has been queued in any buffers.
When the output buffer is filled, or when the stream is closed, it is automatically flushed. The standard output is also automatically flushed by certain sequences, like endl. But you can trigger a flush of the standard output at any point by called cout.flush() or by using the flush manipulator, like:
cout << 'X' << flush;
I am trying to time a code I've got in C++. I have an inner and an outer loop that I want to time separately, but at the same time. For some reason when I do this one of the instances returns 1.84467e+13 and always this exact number.
Why is this happening?
Here is a minimum working example that replicates the effect on my machine:
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
long int i, j;
clock_t start, finish, tick, tock;
double a = 0.0;
double adding_time, runtime;
start = clock();
for(i=0; i<10; i++)
{
a=0.0;
tick =clock();
for(j=0; j<10000000; j++)
{
a+=1;
}
tock= clock();
adding_time = (double)(tick - tock)/CLOCKS_PER_SEC;
cout << "Computation time:" << adding_time << endl;
}
finish = clock();
runtime = (double)(finish - start)/CLOCKS_PER_SEC;
cout << "Total computation time:" << runtime << endl;
}
Your clock_t is apparently an unsigned 64-bit type.
You're taking tick - tock, where tock was measured after tick, so if there's any difference between the two at all, it's going to try to produce a negative number--but since it's an unsigned type, that's wrapping around to become something close to the largest number that can be represented in that type.
Obviously, you really want to use tock-tick instead.
let say tic = 2ms and tac is 4ms; so when you do tic-tac(2-4) that will generate a negative number obviously.. even if it given a positive number it wont be the real time. and also, the number it generate (which doesnt appear on my computer) is a big number, so, try to use the manipulator;
#include"iomanip"
cout << fixed << showpoint;
cout << setprecision(2);
it might work..
I'm writing a code to output fibonacci series in C++, which is simple enough, but since I'm new to programming, I'm considering ways to control
I was wondering if there's a way to control time for when outputs come out without processing time being included (e.g. If it takes .0005 seconds to process my input and I want it to repeat the output in 1 second rather than 1.0005 seconds).
I also am wondering if there's a way to just have it output (say 1) and then have it wait for me to press enter, which will make it output the second part (2).
Also, I'd appreciate any other suggestions on how to control output.
If you're on Windows, a quick way to pause is to call system("pause"); This isn't a very professional way of doing things, however.
A way to pause with the std namespace would be something like this:
cout << "Press Enter to continue . . ." << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
As for your main question... If you're just dealing with text output to the user, it's not possible for them to notice a five microsecond delay. They can notice if your interval lengths fluctuate by tens of milliseconds, however. This is why sleep(..) functions sometimes fail.
Let's take your example of wanting to output another number in the Fibonacci sequence once per second. This will work just fine:
#include <ctime>
#include <limits>
#include <iostream>
void pause() {
std::cout << "Press Enter to continue . . ." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
int main() {
clock_t next = clock();
int prev1, prev2, cur = 0;
for (int i = 0; i < 47; ++i) {
if (i < 2) cur = i;
else cur = prev1 + prev2;
prev2 = prev1;
prev1 = cur;
while (next > clock());
std::cout << (i+1) << ": " << cur << std::endl;
next += CLOCKS_PER_SEC;
}
pause();
return 0;
}
The next number in the sequence is computed and ready to print prior to the wait, thus the computation time will not add any delay to the timed output.
If you want your program to continue outputting at a fixed rate while your program works in the background, you'll need to look into threads. You can have your results added to a queue in one thread, while another thread checks for results to print once per second.