user1296153
user1296153

Reputation: 585

Time lapse code in C++

I had to create timelapse function to wait for X amount of time in a loop.

The following code checks the boolean value of m_abortTimeLapseThread but after running for an hour I noticed the execution time of this code created 10 seconds delay. Is there a way to check m_abortTimeLapseThread as frequently as possible and wait for X amount of time in the function without the kind of delay I observed ?

void Acquisition::TimeLapseCount() {

int max10msWaitTimes = m_timeLapseInMs / 10;
while (true) {

    m_timeLapseImageSaved = true;

    for (int i = 0; i < max10msWaitTimes; i++)
    {
        if (m_abortTimeLapseThread) {
            return;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }


}
}

Thanks,

Upvotes: -1

Views: 1197

Answers (1)

super
super

Reputation: 12968

You could measure total time elapsed.

void Acquisition::TimeLapseCount() {
    auto waitUntil = std::chrono::system_clock::now() + std::chrono::milliseconds(m_timeLapseInMs);
    while (true) {

        m_timeLapseImageSaved = true;

        while (waitUntil > std::chrono::system_clock::now())
        {
            if (m_abortTimeLapseThread) {
                return;
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }

        waitUntil += std::chrono::milliseconds(m_timeLapseInMs);
    }
}

Upvotes: 1

Related Questions