执行/在循环中停留一段时间,例如 1 分钟

Execute / stay in the loop for a defined amount of time e.g 1 minute

本文关键字:例如 分钟 一段时间 停留 循环 执行      更新时间:2023-10-16

我想创建一个c++程序,在定义的时间内运行while循环,然后退出循环。让循环在运行时做一些事情,当达到设置的时间时,它将脱离循环。例如,当循环运行时,它将继续在屏幕上打印内容,当 1 分钟过去时,它将退出循环。

#include <iostream>
#include <time.h>

using namespace std;
int main()
{
    time_t now = time(nullptr);
    tm* current_time = localtime(&now);
    int current_minute = current_time->tm_min;
    int defined_minute = current_minute + 1;
    while (current_minute < defined_minute)
    {
        current_minute = current_time->tm_min;
    }
}

创建了这段代码,它应该可以工作,但它没有,我试图调试,但我仍然不明白为什么它不起作用。

P.S. 这是我第一次在网上发布编程问题,如果有人告诉我将来如何更好地提出我的问题,请表示感谢。

这是最简单的答案:

#include <chrono>
#include <iostream>
int
main()
{
    using namespace std;
    using namespace std::chrono;
    auto finish = system_clock::now() + 1min;
    do
    {
        cout << "stuffn";
    } while (system_clock::now() < finish);
}

这需要 C++14 或 C++17。 如果您使用的是 C++11,请将 minutes{1} 替换为 1min 。 如果您使用的是 C++03,则<chrono>不可用,并且您必须使用 C API 进行计时,这显然更难使用。

这是关于<chrono>的视频教程。

使用 #include <chrono>

auto t0 = std::chrono::system_clock::now();
while ( (std::chrono::system_clock::now()-t0) < std::chrono::minutes{1})
{
    // do stuff
}

这段代码至少需要 C++11,并且可能会计算一些复杂的C++对象,但这是我的想象方式

#include <iostream>
#include <future>     //std::async
#include <atomic>
#include <chrono>
#include <sstream>
int main()
{   
    int i = 0;
    std::stringstream sstr;
    std::atomic<bool> do_it(true);
    //store future so that async returns immediately
    //see Notes paragraph on https://en.cppreference.com/w/cpp/thread/async
    auto fut = std::async(std::launch::async, [&do_it]() {
                                                        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                                                        do_it = false;
                                                    });
    //Preemtion could steal some time here...
    while ( do_it )
    {
        sstr << "Iteration: " << ++i << "n";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    std::cout << sstr.str() << "n" << std::flush;
    std::cout << "Byen" << std::flush;
}

结果是(您可以在像coliru这样的在线C++编译器上尝试一下(

Iteration: 1
...
Iteration: 95
Iteration: 96
Iteration: 97
Iteration: 98
Bye

希望对你有帮助

另一个答案可能是使用条件变量来应对丑陋的sleep_for(...(,就像我的第一个答案一样,由于应用程序/计算所花费的时间,导致只有 98 次迭代而不是 100 次迭代(这里在字符串流中打印一些循环号(。

条件变量可以针对多个线程

#include <iostream>
#include <thread>
#include <condition_variable>
#include <atomic>
#include <chrono>
#include <sstream>
//From https://en.cppreference.com/w/cpp/thread/condition_variable/wait_until
int index[2] = { 0 };
std::stringstream sstr;
std::condition_variable cv;
std::mutex cv_m;
std::atomic<bool> do_it(true);
std::mutex mut_print;
void foo(char id, int * index)
{ 
    if ( ! index ) return;
    auto new_tp = std::chrono::system_clock::now();
    while ( do_it )
    {   
        {
            std::lock_guard<std::mutex> lock(mut_print);
            sstr << "Iteration of "<< id << ": " << ++(*index) << "n";
        }
        new_tp += std::chrono::milliseconds(10);
        while ( do_it )
        {   
            std::unique_lock<std::mutex> lk(cv_m);
            if(std::cv_status::timeout == cv.wait_until(lk,new_tp ) ) {
                break;
            }
        }
    }
}
void signals()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    do_it = false;
    cv.notify_all();
}
int main()
{   
    std::thread t1(foo,'A',&index[0]),t2(foo,'B',&index[1]),ts(signals);
    t1.join();
    t2.join();
    ts.join();
    std::cout << sstr.str() << "n" << std::flush;
    std::cout << "Byen" << std::flush;
}

科里鲁

结果是

Iteration of A: 1
Iteration of B: 1
Iteration of A: 2
Iteration of B: 2
...
Iteration of A: 100
Iteration of B: 100
Iteration of A: 101
Iteration of B: 101
Bye

这次我们在 101 次迭代中走得有点远,但此示例不会假装执行有限/给定的次数