void PauseFor( int seconds)
{
clock_t temp;
temp = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < temp) {}
}
Ok, this is my function.
I want to make stop executing code for 2 seconds in this time do nothing.
Example:
RUN FUNCTION
after firs run , pause 2 seconds.
In this time 2 seconds do nothing.
after 2 seconds, you can run function again.
What i want to to ?
I want to stop using function for 2 seconds, In this time 2 seconds nothing happen..
Thanks :)
MyFunction()
{
//bla bla bla do something
PauseFor(2);
}
First run MyFunction() after first run , 2 seconds can't run.. after 2 seconds run again
Simply, a return false for 2 seconds
Try this
std::this_thread::sleep_for(std::chrono::seconds(2));
Related
This question already has answers here:
Measuring execution time of a function in C++
(14 answers)
Getting an accurate execution time in C++ (micro seconds)
(4 answers)
Closed 2 months ago.
I'm trying to compute the amount of time an algorithm runs in my program, and display that amount in differents meausures such as seconds, miliseconds, microseconds...
This is how I've been approaching it:
auto start = high_resolution_clock::now();
myFunction();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(stop - start);
const auto hrs = duration_cast<hours>(duration);
const auto mins = duration_cast<minutes>(duration - hrs);
const auto secs = duration_cast<seconds>(duration - hrs - mins);
const auto ms = duration_cast<milliseconds>(duration - hrs - mins - secs);
std::cout << "Time needed: "<<hrs.count()<<" hours "<<mins.count()<<" mins "<<secs.count()<<" secs " <<ms.count()<<" milisecs "
What I intend it to do (invented example):
Time needed: 0 hours 1 mins 30 seconds 2400miliseconds
BUt for some reasons it prints all 0s (even miliseconds) when times are <1secs, and when times are 1secs or more, it does not prints the exact time either, it does something like
Time needed: 0 hours 0 mins 1 seconds 1000miliseconds
it just print a whole seconds and then it converts it to the others meausures, but the actual time that I took the function to works is not exactly 1 second, how can I get that? (if theres better ways to do that other than std::chrono I'll be interested too)
I need to get the elapsed time from a while.
something.start()
auto start = std::chrono::steadyt_clock::now();
while(something->is_valid())
{
// getting frames
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
// do something with the frames
if(diff % 3 == 0) { /* do something with the something */ }
}
But it get the time in every ms i get the time and my if statement runs too much. I can not use std::this_thread::sleep_for() cause i need every frame to catch. How can i do it pararell?
Since C++14 you could do diff >= 3s to see if the difference was equal or bigger than three seconds (see this duration literal reference).
Otherwise if you're stuck with C++11 then use diff >= std::chrono::seconds(3).
Note that this requires you to reset start each time the condition is true:
if (diff >= 3s)
{
start = end;
// Do something with the something...
}
This is required because the difference could stay equal to 3 (and therefore diff % 3s == 0 being true) for up to a whole second, which means your "Do something..." part will execute many times falsely.
I want to run a loop inside a thread that calculates some data every millisecond. But I am having trouble with the sleep function. It is sleeping much too long.
I created a basic console application in visual studio:
#include <windows.h>
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
typedef std::chrono::high_resolution_clock Clock;
int _tmain(int argc, _TCHAR* argv[])
{
int iIdx = 0;
bool bRun = true;
auto aTimeStart = Clock::now();
while (bRun){
iIdx++;
if (iIdx >= 500) bRun = false;
//Sleep(1);
this_thread::sleep_for(chrono::microseconds(10));
}
printf("Duration: %i ms\n", chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - aTimeStart).count());
cin.get();
return 0;
}
This prints out: Duration: 5000 ms
The same result is printed, when i use Sleep(1);
I would expect the duration to be 500 ms, and not 5000 ms. What am I doing wrong here?
Update:
I was using Visual Studio 2013. Now I have installed Visual Studio 2015, and its fine - prints out: Duration: 500 ms (sometimes its 527 ms).
However, this sleep_for still isn't very accurate, so I will look out for other solutions.
The typical time slice used by popular OSs is much longer than 1ms (say 20ms or so); the sleep sets a minimum for how long you want your thread to be suspended not a maximum. Once your thread becomes runnable it is up to the OS when to next schedule it.
If you need this level of accuracy you either need a real time OS, or set a very high priority on your thread (so it can pre-empt almost anything else), or write your code in the kernel, or use a busy wait.
But do you really need to do the calculation every ms? That sort of timing requirement normally comes from hardware. What goes wrong if you bunch up the calculations a bit later?
On Windows, try timeBeginPeriod: https://msdn.microsoft.com/en-us/library/windows/desktop/dd757624(v=vs.85).aspx
It increases timer resolution.
What am I doing wrong here?
Attempting to use sleep for precise timing.
sleep(n) does not pause your thread for precisely n time then immediately continue.
sleep(n) yields control of the thread back to the scheduler, and indicates that you do not want control back until at least n time has passed.
Now, the scheduler already divvies up thread processing time into time slices, and these are typically on the order of 25 milliseconds or so. That's the bare minimum you can expect your sleep to run.
sleep is simply the wrong tool for this job. Never use it for precise scheduling.
This thread is fairly old, but perhaps someone can still use this code.
It's written for C++11 and I've tested it on Ubuntu 15.04.
class MillisecondPerLoop
{
public:
void do_loop(uint32_t loops)
{
int32_t time_to_wait = 0;
next_clock = ((get_current_clock_ns() / one_ms_in_ns) * one_ms_in_ns);
for (uint32_t loop = 0; loop < loops; ++loop)
{
on_tick();
// Assume on_tick takes less than 1 ms to run
// calculate the next tick time and time to wait from now until that time
time_to_wait = calc_time_to_wait();
// check if we're already past the 1ms time interval
if (time_to_wait > 0)
{
// wait that many ns
std::this_thread::sleep_for(std::chrono::nanoseconds(time_to_wait));
}
++m_tick;
}
}
private:
void on_tick()
{
// TEST only: simulate the work done in every tick
// by waiting a random amount of time
std::this_thread::sleep_for(std::chrono::microseconds(distribution(generator)));
}
uint32_t get_current_clock_ns()
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
}
int32_t calc_time_to_wait()
{
next_clock += one_ms_in_ns;
return next_clock - get_current_clock_ns();
}
static constexpr uint32_t one_ms_in_ns = 1000000L;
uint32_t m_tick;
uint32_t next_clock;
};
A typical run shows a pretty accurate 1ms loop with a 1- 3 microsecond error. Your PC may be more accurate than this if it's a faster CPU.
Here's typical output:
One Second Loops:
Avg (ns) ms err(ms)
[ 0] 999703 0.9997 0.0003
[ 1] 999888 0.9999 0.0001
[ 2] 999781 0.9998 0.0002
[ 3] 999896 0.9999 0.0001
[ 4] 999772 0.9998 0.0002
[ 5] 999759 0.9998 0.0002
[ 6] 999879 0.9999 0.0001
[ 7] 999915 0.9999 0.0001
[ 8] 1000043 1.0000 -0.0000
[ 9] 999675 0.9997 0.0003
[10] 1000120 1.0001 -0.0001
[11] 999606 0.9996 0.0004
[12] 999714 0.9997 0.0003
[13] 1000171 1.0002 -0.0002
[14] 999670 0.9997 0.0003
[15] 999832 0.9998 0.0002
[16] 999812 0.9998 0.0002
[17] 999868 0.9999 0.0001
[18] 1000096 1.0001 -0.0001
[19] 999665 0.9997 0.0003
Expected total time: 20.0000ms
Actual total time : 19.9969ms
I have a more detailed write up here:
https://arrizza.org/wiki/index.php/One_Millisecond_Loop
I have written my own sleep function and want to test it. Following is my code:
func TestSleep(t *testing.T) {
start := time.Now()
mySleepFunction(65)
end := time.Now()
if (end - start) != 65 {
t.Error("Incorrect sleep function")
}
}
This is not working. I am trying to get start time and end time and then compare it with expected time. The expected time will be in seconds. I tried end.Sub(start) but this returns me something like 1m30.0909, instead I need 90 as a result. It would be great if someone could help me.
Thanks :)
Elapsed time:
The easiest to get the elapsed time since a specific time (start) is to use the time.Since() function which returns a time.Duration which has a Duration.Seconds() method which returns the duration in seconds as float64.
So in your case the elapsed seconds:
sec := time.Since(start).Seconds()
Now on to testing...
When testing sleep-like functions you should take into consideration that after the sleep it is not guaranteed that the code will continue to execute immediately. For example quoting from the doc of time.Sleep():
Sleep pauses the current goroutine for at least the duration d.
So when writing test code for sleep-like functions, I would test like this:
elapsed time should be at least the specified,
and allow some error margin.
So for example test it like this:
func TestSleep(t *testing.T) {
const secSleep = 65.0
start := time.Now()
mySleepFunction(int(secSleep))
sec := time.Since(start).Seconds()
if sec < secSleep || sec > secSleep*1.05 {
t.Error("Incorrect sleep function")
}
}
If you use time.Unix() which gives you the amount of seconds since the epoch (January 1, 1970 UTC.) then your test should work.
func TestSleep(t *testing.T) {
start := time.Now().Unix()
mySleepFunction(65)
end := time.Now().Unix()
if (end - start) != 65{
t.Error("Incorrect sleep function")
}
}
Currently, your code is subtracting a time.Now() which doesn't return the result you intend. Your test wants simple int values that represent seconds.
I have a loop and in every loop I get the current seconds the application has been running for I then want to convert this time into how many, Days, Hours and Seconds that the seconds calculate to but not 'real time' I need to be able to customize how many seconds are in a day, I have tried examples on SO and the web but nothing seems to be out there for this. I have some defines
#define DAY 1200
#define HOUR DAY / 24
#define MINUTE HOUR / 60
#define SECOND MINUTE / 60
So in my define a day would last for 1200 seconds. I have then been trying to convert elapsed seconds into 'my' seconds
seconds_passed = fmodf(SECOND, (float)(GetTicks() / 1000));
Which returns what SECOND equals (0.013889) but then every loop is the same, it never changes I was thinking I would just be able to convert for example: 1real second into 1.25fake seconds then
Minute = (seconds_passed / MINUTE);
seconds_passed = fmodf(seconds_passed, MINUTE);
work out how many (fake)minutes, (fake)hours and (fake)days have elapsed since the application started.
Hope that makes sense, thank you for your time.
Since you want to customise how many seconds are in a day, all you're really doing is changing the ratio of 1 second : 1 second.
For instance, if you did was 1200 seconds in a day your ratio is:
1:72
that is, for every 1 second that passes in your day, it is the equivilent of 72 real seconds.
So yes basically all you need to do in your program is find the ratio of 1 second to 1 second, times your elapsed seconds by that to get the 'fake' seconds, and then use that value...
The code may look something like this:
// get the ratio second:fake_second
#define REAL_DAY_SECONDS 86400
int ratio = REAL_DAY_SECONDS / DAY;
fake_to_real = fake_second*ratio;
real_to_fake = real_second/ratio;
You can make your own time durations with one line in chrono:
using fake_seconds = std::chrono::duration<float, std::ratio<72,1>>;
Some sample code
#include <iostream>
#include <chrono>
using namespace std::chrono_literals;
using fake_seconds = std::chrono::duration<float, std::ratio<72,1>>;
int main()
{
auto f_x = fake_seconds(350s);
std::cout << "350 real seconds are:\n" << f_x.count() << " fake_seconds\n";
}
https://godbolt.org/z/f5G86avxr