C++ Timer implementation - c++

I'm trying to implement a "timer" function in C++ for the program to do something after some seconds.
However, I've got unexpected results.
short e, sum;
clock_t start;
double duration=0;
for (e=0; e<4; e++) {
start = clock();
while (duration < 1) {
duration = (clock() - start)/(double)CLOCKS_PER_SEC;
}
cout << duration;
duration = 0;
sum += e;
/* Calculate EPOCH error */
cout << e;
}
cout << "\n" << e<< "\n";
The results I expect are:
console output every second, followed by e (0,1,2,3)
at the end of the execution I expect sum to be 0+1+2+3 = 6,
Results obtained:
console output followed by e, all together when execution finishes
sum = 6
What I find uncertain is, why do the program prints to console until execution is finished and not every second as expected?
Cheers,

Your problem is that the output stream isn't flushed during your loop. Actually writing pieces of text to the console is somewhat expensive. Therefore the input is buffered and only written to the console when a flush occurs. Flushing the stream can be accomplished by streaming std::flush:
cout << e<<std::flush;
std::endl will also flush the stream in addition to adding a newline (writing \n might also do it, but that's not guaranteed).
As a sidenote: you might want to consider adding some sort of seperators between your numbers to make the output readable.

Related

Design of a simple progress bar to cout goes from 0->100% instantly at the end in C++

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;

Printing array elements in one second intervals using sleep()

I have an array that contains chars.
I am trying to print out an element once every second.
int i=0;
while (i< 110)
{
cout << arrayValue[i]<<"\0";
sleep(1);
i++;
}
This for some reason just waits for 110 seconds and than prints out the whole array at once.
But if i add a new line after every element it works just fine
int i=0;
while (i< 110)
{
cout << arrayValue[i]<<"\0";
cout<< endl;
sleep(1);
i++;
}
Any recommendation on how to get each element to print chronologically without having to make a newline?
This for some reason just waits for 110 seconds and than prints out the whole array at once.
Actually it doesn't, but your output is buffered. There is buffering in the C++ stream object, in the OS data pipe, and in your terminal.
Your stream thinks it would be a waste of resources passing characters through one at a time, and it's kind of right: the stream doesn't know you have a second to wait in between each one.
You don't need the newline, though; you can basically force a flush like so:
std::cout << std::flush;
Recall that std::cout << std::endl is equivalent to std::cout << '\n' << std::flush, and it's the '\n' part that you don't want.
This is usually enough but you may also need to reconfigure your terminal to turn off line buffering. (That's unlikely for output but quite common for input).

Cout won't print text without endl inside while loop?

I don't know if it's related to flush in ostream. Since, endl is end with flush right? I don't know what is flush and how it works.
I have a function that will print out each characters of string every second. I want to print it out whitout new line after every characters. Then, I write this function:
using namespace std;
void print_char_per_second (string text) {
int i = 0;
int len = static_cast<int>(text.length());
while (i < len) {
int tick = clock() % CLOCKS_PER_SEC;
if (tick == 0) {
cout << text[i];
i++;
}
}
}
It prints the text one after while loop finished looping and prints all of characters in the text at once. Why this is happen?
Flushing makes sure all output written to the stream so far is shown on the console.
You can do std::cout << std::flush or std::cout.flush() after each output operation to make sure the output is shown on the console immediately.
Right now it's just writing everything to the stream and only flushing the stream after the loop.

C++ Code to calculate sum of unknown number of numbers

Im trying to write a code in c++ that takes an unknown number of numbers and adds them all together. I do not get any errors but when i input numbers it wont do anything.
#include <iostream>
int main()
{
int sum = 0, val;
while (std::cin >> val)
sum += val;
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
My guess is you never ended your input. It will continue looping and adding numbers until you trigger end of file. Just pressing enter won't do that - you need to hit ctrl+d on Linux or ctrl+z on Windows to end the standard input file, allowing the while loop to exit.

Controlling output of program

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.