国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

用JNI實現一個高精度的Java計時器

2019-11-18 15:34:07
字體:
來源:轉載
供稿:網友
    在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的代碼


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新龙县| 甘泉县| 德昌县| 广平县| 牡丹江市| 连山| 随州市| 哈巴河县| 手游| 烟台市| 龙泉市| 府谷县| 互助| 新疆| 河北区| 阿尔山市| 宁阳县| 孙吴县| 武邑县| 清徐县| 确山县| 汝城县| 定远县| 大连市| 会宁县| 叙永县| 神池县| 克山县| 常德市| 虞城县| 大姚县| 舟山市| 武陟县| 鹿邑县| 襄垣县| 西昌市| 商南县| 潞城市| 六安市| 北京市| 霸州市|