Delay in Dev C++ - c++

I have come across to a problem while coding in C++ on Dev C++ compiler. I want to delay my statement to some milliseconds, but the problem is dev doesnt support the dos.h header file and so its contents as well. I had an alternative way for using it with the help of for loop but i aint got its proper syntax in my mind to use it properly. I wish, you folks, might be able to resolve the problem for me. Thanks in Advance..
#include <dos.h>
int main(){
delay(1000)
cout << "Hello"
return 0;
Tell me another alternative way for this please.

C++ has < thread >
< thread > has "std::this_thread::sleep_for(...)"
Example illustrating the (...)
std::this_thread::sleep_for(100ms);
The ms of 100 ms comes from
using namespace std::chrono_literals; // support suffixes like 100ms, 2s, 30 us
Probably you also need to include < chrono >

Use the header chrono and thread
#include <iostream>
#include <thread>
#include <chrono>
using namespace std::this_thread;
using namespace std::chrono;
sleep_for(nanoseconds(10));
sleep_until(system_clock::now() + seconds(1));
You can change the nanoseconds part to seconds or keep it at nanoseconds, and the number beside it is the amount of that unit that you can change to any number.

Use empty for loop
for example:
for(int i=0; i<10000; i++);
Change upper bound according to your need.

Related

Delay in CodeWarrior

I am new to trying to write anything. While I can read what's happening most of the time, I have no idea how to build a delay. In Arduino I have used delays but it doesn't seem to work the same here.
I have been searching the internet trying to find something that will work, but with no luck. I think I could make something work but I don't know how to add more '#includes' either. Currently I have-
#include <xbee_config.h>
#include <types.h>
#include <utils.h>
#include <xbee/atcmd.h>
I have the general idea of what is needed but now idea how to write it. I'm turning on an LED that I need delayed before turning off.
gpio_set(LED1, 1); //Turn on LED
**Delay here!!!!**
gpio_set(LED1, 0); //Turn off LED
My first thought is building a void_delay function that will increment a counter until x time is reached, then return to the program. I know that's not the best way as it will be keeping the program from other tasks while counting, but it should work for my purpose. The problem, I have no idea how to write that.
In c++ you can use Sleep(milliseconds) you only have to include <windows.h>.
Example:
#include <iostream>
#include <windows.h>
using namespace std;
int main() {
cout << "Before delay" <<endl;
Sleep(5000);
cout << "After delay" <<endl;
return 0;
}

How to measure time cost of multithreading program on Mac OS using C++?

I'm writing a multithreading program on Mac OS using C++, and I need to measure time cost of it.
Here I found some functions maybe useful to measure time:
clock(): for a multithreading program, it's not accurate.
time(): it can measure time but only have second precision.
gettimeofday(): I wrote a sample to test it, but got wrong time measurement.
#include <stdio.h>
#include <iostream>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int main()
{
timeval start, finish;
gettimeofday(&start,NULL);
sleep(10); //sleep for 10 sec
gettimeofday(&finish,NULL);
cout<<(finish.tv_usec-start.tv_usec)/1000.0<<"ms"<<endl;
return 0;
}
The output is just few ms, I don't know why.
Does anyone know any other function to measure time on Mac OS?
Each of the values is looping - when msecs gets to 1000, secs is incremented and msecs is set back to 0. When secs hits 60, mins is incremented and secs gets set back to 0.
If you are trying to measure time this way, you need to take all the fields bigger than your required minimum resolution into account.
struct timeval has two fields, tv_sec and tv_usec. You're ignoring tv_sec, thereby throwing away the most significant part of the time.
The best solution is to use the <chrono> functionality (that of course implies that you're using a c++11-enabled compiler).
Then you code might look like:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
int main()
{
auto start = high_resolution_clock::now();
std::this_thread::sleep_for(10s); //sleep for 10 sec
cout << duration_cast<milliseconds>(high_resolution_clock::now() - start).count() << "ms\n";
return 0;
}
Note that I'm also using neat chrono literals to specify 10s, which is c++14 feature. If it's not available, just use seconds(10) instead.
Note, however, that the output is not guaranteed to be "10000ms" as the OS is allowed to suspend the thread for longer - see here (unistd one also doesn't guarantee that).
Cheers,
Rostislav.

Cross platform way to prevent high cpu usage in while loop (Without boost)?

I have a server that I want to run, and it uses a cross platform library that only gives me a tick() to call:
int main()
{
Inst inst;
while(true)
{
inst.tick();
}
}
I need to try to lower the cpu usage so that it doesnt constantly take up 1 core.
Is there a simple way to do this without boost?
Thanks
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
//5 seconds
auto duration = chrono::duration<float>(5);
this_thread::sleep_for(duration);
return 0;
}
However, even if this code is completely fine, I can't seem to compile it with the provided MinGW compiler from Code::Blocks.

srand(time(NULL)) "Function 'srand' could not be resolved."

I have been trying to debug this problem for a while and quite honestly, I just can't see what I'm doing wrong.
Why is there a syntax error?
#include <iostream>;
#include <time.h>;
#include <stdio.h>;
#include <stdlib.h>;
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
The error I'm getting is,
"Function 'srand' could not be resolved."
I'm well aware now that I don't need the semi-colons after 'include' statements
I'm using Eclipse CDT along with MinGW as my compiler
How I resolved the problem:
It had to do with the MinGW compiler I was using. Switching over to Visual Studio solved the problem.
; at the end of the #include directives are the problem in your code. #include directives don't need (wrong to place indeed) semicolons at the end unlike C++ statements.
[Warning] extra tokens at end of #include directive [enabled by default]
It seems any character after > in the directive causes this error/warning.
#include<iostream>a //error
Change to this:
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
int main(){
cout<<"Hello Main";
}
EDIT:
Regarding the linker issue:
One suggestion is C++ expects types to be explicitly casted between types (more than C). So, use a cast to convert time_t which is returned by the time to unsigned int which is the input parameter type of srand. (And of course this might not be the problem with linker error)
Instead of using stdlib.h, try using <cstdlib>, try if it helps. Because it uses namespace.
Apart from that, I have seen this snippet here. Use that pattern if it helps.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); //use current time as seed for random generator
int random_variable = rand();
cout << "Random value on [0 " << RAND_MAX << "]: "
<< random_variable << '\n';
}
there is already question in SO check if that helps Eclipse Method could not be resolved in a simple program C++
Never use time() to initialize srand()..
EDIT:
Now it seems many people got this kind of problem. I found a question How do I fix Eclipse CDT Error “Function 'isdigit' could not be resolved. He is facing the same problem. The asker suggested a work around to this in his question edit.
Quoted from that question:
I now believe this to be a Code Analysis problem. A better solution is
to edit the Code Analysis options to make "Function could not be
resolved" be a warning instead of an error. That way you can see the
warnings in Problems view, but continue to work. If the function is
REALLY missing, the compiler will tell you! I also have a new theory,
that the problem is with the Code Analyzer following symlinks, because
all of the "missing" functions are in symlinked include files. Would
love any input on this theory.
Hope that points to solve the problem.
; should not be there after #include.
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include files shoule not end with ;

namespace usage

I'm trying to start using namespaces the correct (or at least best) way.
The first thing I tried to do was to avoid putting using namespace xxx; at the beginning of my files. Instead, I want to using xxx::yyy as locally as possible.
Here is a small program illustrating this :
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
using std::cout;
using std::endl;
srand(time(0));
for(int i=0; i<10;++i)
cout << rand() % 100 << endl;
return 0;
}
If I omit the lines using std::cout; or using std::endl, the compiler will complain when I'm trying to use cout or endl.
But why is this not needed for srand, rand and time ? I'm pretty sure they are in std, because if I try to specifically pour std:: in front of them, my code is working fine.
If you use cstdlib et al. the names in them are placed in both the global and the std:: namespaces, so you can choose to prefix them with std:: or not. This is seen as a feature by some, and as a misfeature by others.
If you really want to know, take a close look at the ctime and cstdlib headers. They were built backwards-compatible.
Note: all this using vs. using namespace business is about readability. If your IDE would allow to just not show the namespaces when you don't want to see them, you wouldn't need these constructs...
I prefer to omit using and just have the std::cout every time just to maintain readability. although this is probably only useful in larger projects
As long as we on the subject, there's also a thing called Koenig Lookup which allows you to omit a namespace identifier before a function name if the arguments it take come from the same namespace.
For example
#include <iostream>
#include <algorithm>
#include <vector>
void f(int i){std::cout << i << " ";}
int main(int argc, char** argv)
{
std::vector<int> t;
// for_each is in the std namespace but there's no *std::* before *for_each*
for_each(t.begin(), t.end(), f);
return 0;
}
Well, it's not related directly but I though it may be useful.