为什么c++中的clock_gettime给我的值与Java的nanotime()不同?

Why is the clock_gettime in C++ giving me different values compared to Java nanotime()

本文关键字:nanotime Java 不同 clock 中的 c++ gettime 我的 为什么      更新时间:2023-10-16

所以我有这段我曾经在Java游戏中执行跳跃时使用的旧代码。

它看起来像这样:

//Vars
final int Y_ZERO_POINT = 580;
double height = 0, speed = 4;
public static final double gravity = 9.81;
double x = 25;
int y = (int) (Y_ZERO_POINT-(height*100));
long previous, start = 0;
// Code in my game loop
        start = System.nanoTime();
        if(previous != 0 && up){
            double delta = start - previous;
            height = (height + (delta/1000000000) * speed);        
            speed -= (delta/1000000000)  * gravity;
            y = (int) (Y_ZERO_POINT-(height * 100));
        }
        previous = start;

现在我想在c++游戏中实现类似的东西。阅读此处:http://www.javacodegeeks.com/2012/02/what-is-behind-systemnanotime.html我了解到Java System.getNanoTime()在Linux系统中使用clock_gettime(CLOCK_MONOTONIC, &ts);

所以我在我的c++代码中使用了它,并实现了相同的跳转代码:https://github.com/Veske/CPP-Learning/blob/master/kodutoo3/player/player.cpp

差异是巨大的。在Java中,跳转总是一致的,并按其应有的方式结束。在我的c++程序中,跳转有时就像在Java中一样,但大多数情况下它会有根本的变化。我从clock_gettime()中获得的时间有时会跳跃很多,这导致游戏中的跳跃本身看起来也非常随机。角色有时会跳出屏幕,然后下一次又正常跳出。

是否有可能从c++时间函数中获得一致的结果,就像在Java中一样,或者我是否应该考虑为我的跳跃机制使用不同的方法?

如果你有c++ 11编译器,你可以使用可移植的<chrono>头文件

[在线运行]

#include <iostream>
#include <chrono>
using namespace std;
int main()
{
    auto t0 = chrono::steady_clock::now();
    auto t1 = chrono::steady_clock::now();
    auto dt = t1 - t0;
    cout << "t0: " << chrono::time_point_cast<chrono::nanoseconds>(t0).time_since_epoch().count() << " ns" << endl;
    cout << "t1: " << chrono::time_point_cast<chrono::nanoseconds>(t1).time_since_epoch().count() << " ns" << endl;
    cout << "dt: " << chrono::duration_cast<chrono::nanoseconds>(dt).count() << " ns" << endl;
    return 0;
}
样本输出:

t0: 2800906746162 ns
t1: 2800906746345 ns
dt: 183 ns
对于时差测量,请确保使用不可调(又称单调)时钟,如steady_clock