How come this program waits 10 seconds instead of counting down? - c++

I was trying out some c++11 code, and I tried to write a program that counts down from 10, sleeping in between the outputs. Here's what I have so far:
#include <iostream>
using namespace std;
#include <chrono>
#include <thread>
void Sleep(int x)
{
std::this_thread::sleep_for(std::chrono::duration<int>(x));
}
int main()
{
for (int x=10; x>0; x--) {
cout << x << "...";
Sleep(1);
}
cout << " FIRE!!\n";
}
The problem is, this code waits 10 seconds and then prints all of the output, instead of counting down from 10. How come this is? And how can I fix it?
(By the way, I tried this on a computer running Linux Mint 17 and MacOSX 10.9, and both times I got the same result)

Probably because you don't flush the output. Try this
cout << x << "..." << flush;
Stream output can be buffered, which means the results don't always appear immediately. Flushing at least increases the chance that you will see some output immediately.

You need to flush the output each time round the loop, otherwise the runtime system will wait for the buffer to be full or (sometimes) an end of line to be sent.
Also, when using std::chrono::duration<> it is better to use one of the explicitly defined types if possible for readability. In this case you are measuring times in seconds so I used std::chrono::seconds in your example:
#include <iostream>
using namespace std;
#include <chrono>
#include <thread>
void Sleep(int x)
{
// better to use explicit types for duration
// for readability
std::this_thread::sleep_for(std::chrono::seconds(x));
}
int main()
{
for(int x = 10; x > 0; x--) {
cout << x << "..." << std::flush; // need to flush here
Sleep(1);
}
cout << " FIRE!!\n";
}

Related

C++ duration_cast<>(time_point_end - tine_point_start). count() overflows

What I want to do, my project:
I want to make a program that waits 0.5 seconds, for example, does something, let's say cout << "Hello World", once and then again the same for about 10 times(this is a test for another program), but without sleep, sleep_for, sleep or anything similar BCS I don't want the processor to actually sleep, BCS at that time the processor does not just wait, it does nothing for that time, for these 0.5 seconds it does nothing and I don't want that, and the main reason is BCS it also doesn't take input.
What I tried:
What I tried was to keep two points in time(time_point start,end), duration_cast their difference (end - start) in a for loop ((int i = 0;i < 10;i++)), and if their difference was 500 milliseconds, then, cout << "Hello World\n";.
My code looked something like this:
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace chrono;
int main()
{
time_point<steady_clock> t = steady_clock::now():
for (int i = 0; i < 10;)
{
duration<double> d = steady_clock::now() - t;
uint32_t a = duration_cast<milliseconds>(d).count();
if (a >= 500)
{
cout << a << " Hello World!" << endl;
t = steady_clock::now();
i++;
}
}
return 0;
}
My problem:
It overflows, most of the time, I don't know what exactly overflows, but a appears to be sometimes 6??? others 47??? (? = some digit)
I tried many things, I ended up to something like this:
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace chrono;
int main()
{
time_point<high_resolution_clock> t = high_resolution_clock::now();
for (int i = 0; i< 10;)
{
duration<double,ratio<1,1000000>> d = high_resolution_clock::now() - t;
uint32_t a = duration_cast<microseconds>(d).count();
if (d >= microseconds(500000) )
{
cout << a << " Hello World!" << endl;
i++;
t = high_resolution_clock::now();
}
}
return 0;
}
It didn't really solve the problem, but the max value appears is `~1500(1500000 in microseconds) and when it happens it takes longer to print the message, I don't know if its still overflow, to be honest, but...
Question
Anyway, do you have any suggestions about how to stop the overflow or a completely different way to achieve what I want, even if you don't, thanks for spending time to read my question, I hope to express someone else's question if there someone who has the same question as me.
Not sure if this is what you're looking for or not. But if not, maybe we can build on this to figure out what you want:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
auto t = steady_clock::now();
for (int i = 0; i < 10; ++i)
{
auto t1 = t + 500ms;
while (steady_clock::now() < t1)
;
cout << duration<double>(t1-t).count() << " Hello World!" << endl;
t = t1;
}
}
The code sets a time_point for 500ms in the future, and then enters a busy loop until that future time_point is now.

Coroutines2 - why yield runs when no source called

I am learning how to use boost coroutines2 library. I have read some tutorials and started experimenting with it. But then I found something very confusing. Please take a look at this basic example.
#include <boost/coroutine2/all.hpp>
#include <iostream>
using namespace std;
typedef boost::coroutines2::coroutine<int> cr;
void creator(cr::push_type& yield)
{
cout << "First time." << endl;
yield(1);
cout << "Second time. " << endl;
yield(2);
}
int main()
{
cr::pull_type source{creator};
source();
}
The result is, naturally, this:
First time.
Second time.
But, to my surprise, when I remove the 'source' call in the main function, the result is just the same! (According to tutorials, the coroutine is called first time at construction time, so it is ok that it is called, but should be now called only once!)
#include <boost/coroutine2/all.hpp>
#include <iostream>
using namespace std;
typedef boost::coroutines2::coroutine<int> cr;
void creator(cr::push_type& yield)
{
cout << "First time." << endl;
yield(1);
cout << "Second time. " << endl;
yield(2);
}
int main()
{
cr::pull_type source{creator};
}
The result is still:
First time.
Second time.
When I remove the second 'yield' in the coroutine, the result is also the same:
#include <boost/coroutine2/all.hpp>
#include <iostream>
using namespace std;
typedef boost::coroutines2::coroutine<int> cr;
void creator(cr::push_type& yield)
{
cout << "First time." << endl;
yield(1);
cout << "Second time. " << endl;
}
int main()
{
cr::pull_type source{creator};
}
Result:
First time.
Second time.
How is that possible? How does it work? I expected that when I don't call the coroutine, then even if there is another 'yield' waiting, nothing will happen.
And I find also strange this behaviour:
When I add another 'source' statements in the main, the code still prints the same, as at the beginning!
#include <boost/coroutine2/all.hpp>
#include <iostream>
using namespace std;
typedef boost::coroutines2::coroutine<int> cr;
void creator(cr::push_type& yield)
{
cout << "First time." << endl;
yield(1);
cout << "Second time. " << endl;
yield(2);
}
int main()
{
cr::pull_type source{creator};
source();
source();
}
Result:
First time.
Second time.
No error, even when sourcing more times than there are 'yield's.
Only after adding one more 'source' in the main function do I receive a runtime error (This application has requested the Runtime to terminate it in an unusual way...)
int main()
{
cr::pull_type source{creator};
source();
source();
source();
}
Could someone help me please with understanding this behaviour?
The reason lies in a bug in Boost. I checked that in Boost 1.65.1 everything works fine. Here is the proof: https://wandbox.org/permlink/pRuSgnwa3VPdqNUk

How to develop a program that use only one single core?

I want to know how to properly implement a program in C++, in which I have a function func that I want to be executed in a single thread. I want to do this, because I want to test the Single Core Speed of my CPU. I will loop this function(func) for about 20 times, and record the execution time of each repetition, then I will sum the results and get the average execution time.
#include <thread>
int func(long long x)
{
int div = 0;
for(long i = 1; i <= x / 2; i++)
if(x % i == 0)
div++;
return div + 1;
}
int main()
{
std::thread one_thread (func,100000000);
one_thread.join();
return 0;
}
So , in this program, does the func is executed on a single particular core ?
Here is the source code of my program:
#include <iostream>
#include <thread>
#include <iomanip>
#include <windows.h>
#include "font.h"
#include "timer.h"
using namespace std;
#define steps 20
int func(long long x)
{
int div = 0;
for(long i = 1; i <= x / 2; i++)
if(x % i == 0)
div++;
return div + 1;
}
int main()
{
SetFontConsolas(); // Set font consolas
ShowConsoleCursor(false); // Turn off the cursor
timer t;
short int number = 0;
cout << number << "%";
for(int i = 0 ; i < steps ; i++)
{
t.restart(); // start recording
std::thread one_thread (func,100000000);
one_thread.join(); // wait function return
t.stop(); // stop recording
t.record(); // save the time in vector
number += 5;
cout << "\r ";
cout << "\r" << number << "%";
}
double time = 0.0;
for(int i = 0 ; i < steps ; i++)
time += t.times[i]; // sum all recorded times
time /= steps; // get the average execution time
cout << "\nExecution time: " << fixed << setprecision(4) << time << '\n';
double score = 0.0;
score = (1.0 * 100) / time; // calculating benchmark score
cout << "Score: ";
SetColor(12);
cout << setprecision(2) << score << " pts";
SetColor(15);
cout << "\nPress any key to continue.\n";
cin.get();
return 0;
}
No, your program has at least two treads: main, and the one you've created to run func. Moreover, neither of these threads is guaranteed to get executed on particular core. Depending on OS scheduler they may switch cores in unpredictable manner. Though main thread will mostly just wait. If you want to lock thread execution on particular core then you need to set thread core affinity by some platform-specific method such as SetThreadAffinityMask on Windows. But you don't really need to go that deep because there is no core switch sensitive code in your example. There is even no need to spawn separate thread dedicated to perform calculations.
If your program doesn't have multiple threads in the source and if the compiler does not insert automatic parallelization, the program should run on a single core (at a time).
Now depending on your compiler you can use appropriate optimization levels to ensure that it doesn't parallelize.
On the other hand what might happen is that the compiler can completely eliminate the loop in the function if it can statically compute the result. That however doesn't seem to be the issue with your case.
I don't think any C++ compiler makes use of multiple core, behind your back. There would be large language issues in doing that. If you neither spawn threads nor use a parallel library such as MPI, the program should execute on only one core.

Why do I need to clear a stringstream variable with each iteration of a loop in which it is used

At my school we have to follow a style guide which states we must declare each variable at the top of the function where it is used, as opposed to right before it is used. This often means you have to reset or clear variables while using them inside loops since they are not declared inside that loop. I don't understand why a stringstream variable needs to be "clear"ed with each loop iteration and was hoping someone could shed light on this. I know how to clear it just want to know why it's necessary.
The rationale behind this is that creating heavy objects inside of the loop leads to performance degradation. ::std::stringstream is one of these objects and it's a common mistake to create and destroy string streams all the time. However such a rule does not apply for light objects, such as primitive types.
Consider the test case:
#include <chrono>
#include <sstream>
#include <iostream>
#include <cstdlib>
int main()
{
using namespace std;
using namespace chrono;
auto const loops_count{1000000};
auto const p1{high_resolution_clock::now()};
{
stringstream ss{};
for(auto i{loops_count}; 0 != i; --i)
{
ss.str(string{}); // clear
ss << 1;
}
}
auto const p2{high_resolution_clock::now()};
{
for(auto i{loops_count}; 0 != i; --i)
{
stringstream ss{}; // recreate
ss << 1;
}
}
auto const p3{high_resolution_clock::now()};
cout << duration_cast< milliseconds >(p2 - p1).count() << "ms "
<< duration_cast< milliseconds >(p3 - p2).count() << "ms"
<< endl;
return EXIT_SUCCESS;
}
first loop 35ms, second 431ms

Why is srand() not being stored in my variable?

This beginner's program I am trying to make is basically a program where a truly random number is generated and the "player" has to guess the number. The computer will respond "too high" or "too low" until the player guesses the right number.
I got this program idea from some website, and thought I should roll with it. This is my second program- my first being a simple I/O program.
Here is my code:
// BracketingSearch.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <istream>
#include <fstream>
using namespace std;
int main()
{
int x = srand(time(0));
cout << x << endl;
for (int x = 1; x <= 10; x++) {
cout << 1 + (rand() % 100) << endl;
}
string stall;
getline(cin, stall);
}
Side notes:
I don't think I need that many headers; I am still getting use to the c++ libraries.
Please critique my code as much as possible. I am eager to learn programming!
The string stall is just to make my console application pause for input, so I can see the results.
Thank you for everyone who can help!
-Mike
srand(time(0)) seeds the random number generated by rand(). Its return type is void. void type cant be stored in an integer type variable.
See here for more information on srand().
I rewrote the program to use the minimum of headers required. Since I think this is homework, I left the original error in place, but placed the error output from gcc here.
#include <iostream>
#include <cstdlib>
#include <ctime>
// this is a personal thing, but I avoid "using namespace std;"
// in any file, since it makes it less clear where some symbols
// came from
int main()
{
int x = std::srand(std::time(0)); // line 11
std::cout << x << std::endl;
for (int x = 1; x <= 10; x++) {
std::cout << 1 + (std::rand() % 100) << std::endl;
}
// Windows folklore -- you should better switch your ide to not close
// the terminal after the program was run
std::cin.get();
}
The output of g++ -Wall foo.cpp:
foo.cpp: In function 'int main()':
foo.cpp:11:40: error: void value not ignored as it ought to be
int x = std::srand(std::time(0));
^