c++

微秒级延时函数

c++

Posted by YiMiTuMi on June 7, 2024

微秒级延时函数

正常用的延时函数精准度太低了,现在提供两种延时,一种是c++ chrono新特性来实现的,一种是windows时钟实现的。

chrono实现

#include <chrono>

void timeUsC(int iTimeUs)
{
	auto start = std::chrono::system_clock::now();
	while (true)
	{
		auto end = std::chrono::system_clock::now();
		auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

		if (duration.count() > iTimeUs)
		{
			break;
		}
	}
}

windows时钟实现

#include <windwos.h>

int timeUsWindows(int us)
{
	LARGE_INTEGER fre;

	if (QueryPerformanceFrequency(&fre)) //判断是否支持
	{
		LARGE_INTEGER run, priv, curr;
		run.QuadPart = fre.QuadPart * us / 1000000;

		QueryPerformanceCounter(&priv);    //获取当前的
		do
		{

			QueryPerformanceCounter(&curr);

		} while (curr.QuadPart - priv.QuadPart < run.QuadPart);

		curr.QuadPart -= priv.QuadPart;
		int nres = (curr.QuadPart * 1000000 / fre.QuadPart);

		return nres;
	}

	return -1;
}