用JNI实现一个高精度的Java计时器
2008-01-05 08:25:50 来源:WEB开发网核心提示: 在java程序中,我们可以用System.currentTimeMillis()来计时,用JNI实现一个高精度的Java计时器,但是精度不高,在我的机子(Pentium M 1.5GHz, WinXP)上,随着多核CPU的普及,这个问题还要进一步严重,精度小于10ms,通过一个简单的Java程序
在java程序中,我们可以用System.currentTimeMillis()来计时,但是精度不高,在我的机子(Pentium M 1.5GHz, WinXP)上,精度小于10ms。通过一个简单的Java程序,我们可以测试
Code highlighting PRodUCed by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static void main(String[] args) {
long begin = System.currentTimeMillis();
long current;
while (begin == (current = System.currentTimeMillis()))
;
System.out.println((current - begin) + " ms");
}
System.currentTimeMillis()大约10ms才变化一次。
10ms的精度在很多情况下是不够用的,比如开发射击类游戏等等。而PC中自身计时器的精度要高很多,即使是WindowsXP提供的计时器也要比Java的System.currentTimeMillis()高太多了。比如用Win32的QueryPerformanceCounter函数,在我的机子上可以得到1ns的精度。计算机越发展,软件利用硬件的程度和效率却越来越差,这一点在Java的身上表现的尤其严重,随着多核CPU的普及,这个问题还要进一步严重。
言归正传,我们来讲怎么利用QueryPerformanceCounter来实现一个native的Java计时器.
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->package cn.pandaoen.timer;
/**
* A Timer class uses native methods to measure times.
*
* @author pan
*/
public class Timer {
private long prev;
public void reset() {
prev = QueryPerformanceCounter();
}
/**
* @return the duration in ms from the point of reset()
*/
public double getDuration() {
long current = QueryPerformanceCounter();
return (current - prev) / frequency;
}
static final double frequency;
static native long QueryPerformanceFrequency();
static native long QueryPerformanceCounter();
static {
System.loadLibrary("extension");
frequency = QueryPerformanceFrequency() / 1000.0;
}
}
Native的代码
Code highlighting PRodUCed by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static void main(String[] args) {
long begin = System.currentTimeMillis();
long current;
while (begin == (current = System.currentTimeMillis()))
;
System.out.println((current - begin) + " ms");
}
System.currentTimeMillis()大约10ms才变化一次。
10ms的精度在很多情况下是不够用的,比如开发射击类游戏等等。而PC中自身计时器的精度要高很多,即使是WindowsXP提供的计时器也要比Java的System.currentTimeMillis()高太多了。比如用Win32的QueryPerformanceCounter函数,在我的机子上可以得到1ns的精度。计算机越发展,软件利用硬件的程度和效率却越来越差,这一点在Java的身上表现的尤其严重,随着多核CPU的普及,这个问题还要进一步严重。
言归正传,我们来讲怎么利用QueryPerformanceCounter来实现一个native的Java计时器.
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->package cn.pandaoen.timer;
/**
* A Timer class uses native methods to measure times.
*
* @author pan
*/
public class Timer {
private long prev;
public void reset() {
prev = QueryPerformanceCounter();
}
/**
* @return the duration in ms from the point of reset()
*/
public double getDuration() {
long current = QueryPerformanceCounter();
return (current - prev) / frequency;
}
static final double frequency;
static native long QueryPerformanceFrequency();
static native long QueryPerformanceCounter();
static {
System.loadLibrary("extension");
frequency = QueryPerformanceFrequency() / 1000.0;
}
}
Native的代码
更多精彩
赞助商链接