c - 用于计算时间流逝的独立于操作系统的 C 库?

标签 c time

所以在我的游戏中,我需要以独立于硬件的方式模拟物理。

我将使用固定时间步长的模拟,但我需要能够计算调用之间耗时。

我试过了,但一无所获:

#include <time.h>
double time_elapsed;
clock_t last_clocks = clock();
while (true) {
  time_elapsed = ( (double) (clock() - last_clocks) / CLOCKS_PER_SEC);
  last_clocks = clock();
  printf("%f\n", time_elapsed);
}

谢谢!

最佳答案

您可以使用 gettimeofday获取秒数加上自纪元以来的微秒数。如果你想要秒数,你可以这样做:

#include <sys/time.h>
float getTime()
{
    struct timeval time;
    gettimeofday(&time, 0);
    return (float)time.tv_sec + 0.000001 * (float)time.tv_usec;
}

起初我误解了你的问题,但你可能会发现以下制作固定时间步长物理循环的方法很有用。

要制作固定时间步长的物理循环,您需要做两件事。

首先,您需要计算从现在到上次运行物理的时间。

last = getTime();
while (running)
{
    now = getTime();
    // Do other game stuff
    simulatePhysics(now - last);
    last = now;
}

然后,在物理模拟中,您需要计算一个固定的时间步长。

void simulatePhysics(float dt)
{
    static float timeStepRemainder; // fractional timestep from last loop
    dt += timeStepRemainder * SIZE_OF_TIMESTEP;

    float desiredTimeSteps = dt / SIZE_OF_TIMESTEP;
    int nSteps = floorf(desiredTimeSteps); // need integer # of timesteps

    timeStepRemainder = desiredTimeSteps - nSteps;

    for (int i = 0; i < nSteps; i++)
        doPhysics(SIZE_OF_TIMESTEP);

}

使用此方法,您可以为正在执行物理(在我的示例中为 doPhysics)的任何对象提供固定的时间步长,同时通过计算自上次运行物理以来要模拟的正确时间步数来保持实时和游戏时间之间的同步.

关于c - 用于计算时间流逝的独立于操作系统的 C 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2977659/

相关文章:

mysql - 如何在Mysql中执行time_to_month?

algorithm - 下面给出的代码超出了时间限制

date - 根据 Google 表格中的当前日期和时间选择 "Time Description"(VLookup、查询)

java - 我可以使用什么库来解析 Java 中的 Schedule String

c - "int a=({10;});"这个表达式用C语言怎么解释?

c - 使用 C 语言的 GNU 科学库进行线性拟合

c - C是如何标准化的?

c# - 在控制台中刷新值

c - 使用 openMP 任务时出现意外行为

c++ - HPET 的频率 vs CPU 频率用于测量时间