Windows延时
static void sleep_micro_seconds(ULONG ulMicroSeconds)
{
LARGE_INTEGER varFrequency = { 0 }, varCounter_Start = { 0 }, varCounter_End = { 0 };
LONGLONG llCount = 0;
::QueryPerformanceFrequency(&varFrequency);
::QueryPerformanceCounter(&varCounter_Start);
while (true)
{
::QueryPerformanceCounter(&varCounter_End);
llCount = varCounter_End.QuadPart - varCounter_Start.QuadPart;
if (1000000 * llCount > ulMicroSeconds* varFrequency.QuadPart)
{
break;
}
}
}
boost 延时
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>
#define BOOST_DATE_TIME_SOURCE
boost::posix_time::ptime time_now,time_now1;
boost::posix_time::millisec_posix_time_system_config::time_duration_type time_elapse;
// 这里为微秒为单位;这里可以将microsec_clock替换成second_clock以秒为单位;
time_now = boost::posix_time::microsec_clock::universal_time(); //local_time
// sleep 100毫秒;
boost::this_thread::sleep(boost::posix_time::millisec(100));
time_now1 = boost::posix_time::microsec_clock::universal_time(); //local_time
time_elapse = time_now1 - time_now;
// 类似GetTickCount,只是这边得到的是2个时间的ticket值的差,以微秒为单位;
int ticks = time_elapse.ticks();
// 得到两个时间间隔的秒数;
int sec = time_elapse.total_seconds();
Linux C 延时
int clock_gettime(clockid_t clk_id,struct timespec *tp);
clk_id : 检索和设置的clk_id指定的时钟时间。
CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户改成其他,则对应的时间相应改变。
CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响。
CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间。
CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
struct timespec time1 = {0, 0};
struct timespec time2 = {0, 0};
float temp;
clock_gettime(CLOCK_REALTIME, &time1);
usleep(1000);
clock_gettime(CLOCK_REALTIME, &time2);
temp = (time2.tv_nsec - time1.tv_nsec) / 1000000;
printf("time = %f ms\n", temp);
return 0;
}
试试
void sleep_micro_seconds_c(unsigned long ulMicroSeconds)
{
struct timespec time1 = { 0, 0 };
struct timespec time2 = { 0, 0 };
long lCount = 0;
clock_gettime(CLOCK_MONOTONIC, &time1);
while (true)
{
clock_gettime(CLOCK_MONOTONIC, &time2);
lCount = (time2.tv_nsec - time1.tv_nsec) / 1000;
if (lCount > ulMicroSeconds)
{
break;
}
}
}