簡體   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