【问题标题】:How to query the high-resolution performance counter如何查询高分辨率性能计数器
【发布时间】:2012-05-10 00:03:42
【问题描述】:

早上好,

我需要获取 CPU 高分辨率性能计数器的值,以便测量各种软件应用程序之间的延迟。在我的 c(++|#) 中,我使用

BOOL WINAPI QueryPerformanceCounter( __out LARGE_INTEGER *lpPerformanceCount );

WinApi 调用。从java中获取计数器的正确方法是什么?我搜索 jna 没有成功。我知道这是一个特定于平台的问题,但也许有比编写自己的 jni 包装器更快的方法?

最好的祝愿, 阿明

【问题讨论】:

    标签: java winapi


    【解决方案1】:

    使用System.nanoTime怎么样?我认为已经使用了机器的性能计数器,无需编写原生包装器。

    更新:根据“Windows 上的时钟和计时器”部分中的this article on clocks and timers in the jvm

    System.nanoTime() 使用 QueryPerformanceCounter/QueryPerformanceFrequency API 实现

    【讨论】:

    • Jörn,nanoTime() 返回时间,而不是未煮熟的性能计数器。由于我想测量不同应用程序之间的延迟,我需要性能计数器值而不是转换。
    • nanoTime 返回计数器,而不是时间。阅读 javadoc。
    • @Stas 不,它返回PC已经运行的秒数,阅读实现:hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/0cd040567d60/src/…
    • @Motes "QueryPerformanceCounter" 看起来没有任何秒数。而用于定义“has_performance_count”的“QueryPerformanceFrequency”在MSDN上有以下内容:“在运行Windows XP或更高版本的系统上,该函数将始终成功,因此永远不会返回零。”,这意味着has_performance_count始终为真。
    • 代码返回jlong time = (jlong)((current/freq) * NANOSECS_PER_SEC);
    【解决方案2】:

    这是本机包装代码

    1) 文件 W32Call.java

    package jmSense.Native; public class W32Call {
    public native static long QueryPerformanceCounter( );
    public native static int QueryPerformanceCounterInt32( );
    

    2) 运行 java h 创建包含文件

    3) 从

    创建一个 dll “My Native Extensions.dll”
    #include "stdafx.h"
    #include "windows.h"
    #include "jmSense_Native_W32Call.h" 
    
    JNIEXPORT jlong JNICALL Java_jmSense_Native_W32Call_QueryPerformanceCounter(JNIEnv *, jclass)
    {  
        LARGE_INTEGER g_CurentCount; 
        QueryPerformanceCounter((LARGE_INTEGER*)&g_CurentCount); 
        return g_CurentCount.QuadPart; 
    }
    
    JNIEXPORT jint JNICALL Java_jmSense_Native_W32Call_QueryPerformanceCounterInt32(JNIEnv *, jclass)
    {  
         LARGE_INTEGER g_CurentCount; 
         QueryPerformanceCounter((LARGE_INTEGER*)&g_CurentCount); 
         return g_CurentCount.LowPart;
    }
    

    4) 像这样使用它:

    System.loadLibrary("My Native Extensions");
    System.out.println(W32Call.QueryPerformanceCounter());
    

    很好

    【讨论】:

    • 你为什么要这么做? System.nanoTime 无论如何都使用 QueryPerformanceCounter。只需使用 System.nanoTime。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 2011-10-31
    相关资源
    最近更新 更多