为什么c++中的clock_gettime给我的值与Java的nanotime()不同?
Why is the clock_gettime in C++ giving me different values compared to Java nanotime()
所以我有这段我曾经在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
。
相关文章:
- 在java中解决这段代码时面临循环中的问题
- 尝试用java代码编译和运行c++代码
- 在这种情况下,java对象是否可以调用本机函数
- 在java中读取c++字节的位字段
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 使用已使用 java 编码的 openssl 解码数据
- SWIG Java 在使用 -DSWIGWORDSIZE64 时将int64_t转换为 jlong
- Android Java USB for native cpp
- 在由Sublime文本3编译后在cmd上显示Java程序输出
- C++ equivalent to Java Map getOrDefault?
- C++ 中的 Java 样式枚举
- 是否有技术原因阻止 Java 中的 final C++ 像 const 一样严格?
- 加密在 Windows、C++ 和 Java 中传输中的数据
- Java从C++回调到C++回调
- 在 c++ 中模拟输入并在 JAVA 中读取它?
- 用C++包装 Java 库 (JNI)
- 使用 TreeSet Java 对反转进行计数
- 验证openssl c++中的签名,这是由JAVA DSA签名的?
- 如何通过 JNI 将 C 字符串表情符号传递给 Java
- 为什么c++中的clock_gettime给我的值与Java的nanotime()不同?