繁体   English   中英

如何在C ++ CodeBlock中使用计时器

[英]How to use timer in c++ CodeBlock

K,大家好,我正在尝试做这样的事情:“在计算机屏幕上编写一个程序,在屏幕上显示该消息,以显示课程结束前还有多少时间:如果在课程结束时要打印30分钟以上报告某事...”,所以我尝试了:

#include <iostream>
#include <cstdio>
#include <ctime>

using namespace std;
int main() {
    int startTime = 1, endTime;

    endTime = 30 * 3600;

    clock_t start = clock();


    cout<<"Time: "<< start <<'\n';

    if (start >= 7200)
    {
        // do something
    } else if (start == endTime)
    {
        // do something
    }
}

我希望它显示时间,如果时间==数字,然后做点什么。 尝试过sleep(); 但由于某种原因,我在codeBlock中出错。

我收到“此范围内未声明睡眠”。 尝试包括具有它的库...

如果您使用的是Unix,请#include <unistd.h>

如果是Windows,请#include <windows.h> ,然后使用Sleep()

有很多方法可以做到这一点。 这是其中的2个:

使用boost计时器库,这是更好的方法:
http://www.boost.org/doc/libs/1_53_0/libs/timer/doc/original_timer.html

或者启动一个线程

static const int INTERVAL_SEC = 60;
static void* thread_timer_process(void*)
{
    do 
    {
        // Do something;

        sleep(INTERVAL_SEC);

        // don't forget to put a cancel point in here

    } while(true);  
}

int main()
{
    pthread_t thread_id;
    thread_create(&thread_id, null, thread_timer_process,  NULL);

    // Other things

    pthread_cancel(thread_id);   // interrupt thread running.

    void *result = NULL;        
    pthread_join(thread_id, &result);  // wait for thread ending.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM