Slowing Down C++ with loops

Hey Guys,
For my computer science class, my teacher has assigned us to purposefully slow down a C++ program through loops. He has showed us that he can do it through this method but I have not been able to replicate the same effect. It is supposed to output “hello” because of the flush and then output the “bye” after a little bit. He has said that this happened before and it is caused by something with replit itself, is there some configuration that would allow this form of delay.

#include <iostream>
using namespace std;

int main() {
  cout << "hello " << flush;
  for(int n = 0; n < 400 * 1000000; n++);
  cout << "bye";

  return 0;
}
1 Like

try:

#include <iostream>
#include <chrono>
#include <thread>
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono; // nanoseconds, system_clock, seconds

int main() {
  std::cout << "hello " << std::flush;
  sleep_until(system_clock::now() + seconds(1));
  std::cout << "bye";

  return 0;
}

as detailed here. You are right, I believe it is a replit thing, it may be the compiler optimizing your code and since I’m not great with bash & stuff I can’t help you with that. Anyways, welcome to community! @sonicx180

After testing, replit will kill the signal if it stalls for too long so don’t go too far, but it’s optimizing the loop TMK (another line of thought is that it’s just too fast for an int (32 bit number) to actually slow it down, and adding something like vector pushing will cause an actual delay) since the loop isn’t doing anything, so you need to do something in the loop

#include <iostream>
#include <vector>
std::vector<int> x;

int main() {
  std::cout << "Hello" << std::flush;
  for (int i = 0; i < 100000000; i++) {
      x.push_back(i);
  }
  std::cout << "bye!";
}
3 Likes

By adding:

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

This will allow you to use system(“clear”); which clears the console and sleep(1); which sleeps the desired number of seconds (waits).
IE:

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <iostream>
#include <string>
int main(){
system("clear");
std::cout << "Wow";
sleep(3);
system("clear");
std::cout << "Wowie";
}
2 Likes

:cry: is my answer not good? XD

1 Like

No🙂
Mine is just more simple and easy.

1 Like

oh so sorry to bother :smiley:

simple?

#include <iostream>
#include <thread>
using namespace std;
int main() {
  cout << "hello " << flush;
  this_thread::sleep_for(1s);
  cout << "bye";
}
2 Likes

Well it also adds clear and some other good stuff. Plus every single time you only have to so sleep(1);.

1 Like

That’s basically what I did :smiley: XD

2 Likes