实现应用暂停x毫秒-uSleep和sleepcp

本文介绍了两种实现程序暂停的方法,适用于不同的操作系统。方法1使用了标准库中的`<ctime>`,提供了一个名为sleepcp的函数,实现了在多个平台上暂停执行的功能。方法2针对Windows系统,利用`<windows.h>`库的QueryPerformanceCounter和QueryPerformanceFrequency来精确控制延迟。这两个方法都在测试中成功实现了指定毫秒的暂停。

文章目录

实现应用暂停x毫秒, 使用了,void sleepcp(int milliseconds) 和 void uSleep(int waitTime), 测试成功。

方法1

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

using namespace std;

void sleepcp(int milliseconds);

void sleepcp(int milliseconds) // Cross-platform sleep function
{
    clock_t time_end;
    time_end = clock() + milliseconds * CLOCKS_PER_SEC/1000;
    while (clock() < time_end)
    {
    }
}
int main()
{
    cout << "Hi! At the count to 3, I'll die! :)" << endl;
    sleepcp(3000);
    cout << "urrrrggghhhh!" << endl;
}

方法2

#include <windows.h>

#include <future>

void uSleep(int waitTime) {
    __int64 time1 = 0, time2 = 0, freq = 0;

    QueryPerformanceCounter((LARGE_INTEGER*)&time1);
    QueryPerformanceFrequency((LARGE_INTEGER*)&freq);

    do {
        QueryPerformanceCounter((LARGE_INTEGER*)&time2);
    } while ((time2 - time1) < waitTime);
}

参考

Sleep for milliseconds
c++, usleep() is obsolete, workarounds for Windows/MingW?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值