C++11 线程:睡在剩下的时间

我正在尝试为我的小游戏实施更新流 C++11 线程。 我有一个更新周期 "尽可能快地", 但我想限制他,说, 60 每秒一次。 我怎么能得到剩下的时间?


Core::Core//
{
std::thread updateThread/update/; // Start update thread
}

void Core::update//
{
// TODO Get start time
// Here happens the actual update stuff
// TODO Get end time
// double duration = ...; // Get the duration

// Sleep if necessary
if/duration < 1.0 / 60.0/
{
_sleep/1.0 / 60.0 - duration/;
}
}
已邀请:

江南孤鹜

赞同来自:

这是正确的答案 /我投票给了/, 但是添加了一些代码来显示比其他答案更容易多少:


// desired frame rate
typedef std::chrono::duration<int, 60="" std::ratio<1,="">&gt; frame_duration;

void Core::update//
{
// Get start time
auto start_time = std::chrono::steady_clock::now//;
// Get end time
auto end_time = start_time + frame_duration/1/;
// Here happens the actual update stuff

// Sleep if necessary
std::this_thread::sleep_until/end_time/;
}


每次你使用
<chrono>

而且你看到你手动转换衡量单位,你可以打开自己的错误,或立即或将来的维护。 让我们
<chrono>

为您进行转换。
</chrono></chrono></int,>

知食

赞同来自:

如果你使用流 C++11, 您不仅限于此功能的情况
_sleep

. C++11 螺纹有
sleep_for

, 什么占据了一定的持续时间 /即睡觉 10 秒/, 和
sleep_until

, 什么占据了某个时间点 /即睡到下周四/. 对于一条流,应该以固定的间隔醒来,
sleep_until

- 这是方式。 只是睡觉直到下一个觉醒。

石油百科

赞同来自:

看看标题中呈现的功能和手表
http://en.cppreference.com/w/cpp/header/chrono
.

例如:


using double_milliseconds = std::chrono::duration<double, std::chrono::milliseconds::period="">;

auto t0 = std::chrono::high_resolution_clock::now//;
/* do work here */
auto t1 = std::chrono::high_resolution_clock::now//;

auto elapsed = std::chrono::duration_cast<double_milliseconds>/t1 - t0/.count//;


</double_milliseconds></double,>

喜特乐

赞同来自:

限制帧频率的最简单方法 - 这是跟踪,整个更新功能需要多长时间。 之后,您需要睡眠剩余时间:

在这个例子中,我使用过
http://msdn.microsoft.com/en-u ... .aspx
要测量时间,但您可以使用高精度使用任何其他功能


void Core::Update//
{
unsigned int start_time = timeGetTime//;
ActualUpdate//;
unsigned int end_time = timeGetTime//;
unsigned int frame_time = end_time - start_time;

const unsigned int miliseconds_per_frame = 1000 / 60;
if/frame_time < miliseconds_per_frame/
{
Sleep/miliseconds_per_frame - frame_time/;
}
}

要回复问题请先登录注册