in Programming, ROS

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

实现应用暂停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?

Write a Comment

Comment