FFM 是試圖取代 JNI 的新 API,而 jep 就在這裡。它基本上是呼叫 JVM 以外的函數或存取不受 JVM 管理的記憶體。我想測試 FFM 能否擊敗常規 Java API,下面您可以找到一個使用 FFM 和常規 Math.sin 進行數學 sin 的簡單測試
import java.lang.foreign.FunctionDescriptor; import java.lang.foreign.Linker; import java.lang.foreign.MemorySegment; import java.lang.foreign.SymbolLookup; import java.lang.foreign.ValueLayout; public class FFMSinTest { public static void main(String[] args) throws Throwable { Linker linker = Linker.nativeLinker(); SymbolLookup stdlib = linker.defaultLookup(); // Locate the "sin" function in the C math library MemorySegment sinAddress = stdlib.find("sin").orElseThrow(); FunctionDescriptor descriptor = FunctionDescriptor.of(ValueLayout.JAVA_DOUBLE, ValueLayout.JAVA_DOUBLE); var sinHandle = linker.downcallHandle(sinAddress, descriptor); double angle = Math.PI / 4; // 45 degrees in radians // Timing Java's Math.sin() long javaStartTime = System.nanoTime(); for (int i = 0; i < 1_000_000; i++) { double result = Math.sin(angle); } long javaEndTime = System.nanoTime(); long javaDuration = javaEndTime - javaStartTime; // Timing C sin via FFM long ffmStartTime = System.nanoTime(); for (int i = 0; i < 1_000_000; i++) { double result = (double) sinHandle.invoke(angle); } long ffmEndTime = System.nanoTime(); long ffmDuration = ffmEndTime - ffmStartTime; System.out.println("Java Math.sin() took: " + javaDuration / 1_000_000.0 + " ms"); System.out.println("C sin (FFM) took: " + ffmDuration / 1_000_000.0 + " ms"); } }
結果是
Java Math.sin() took: 4.8677 ms C sin (FFM) took: 78.9172 ms
在我的筆記型電腦上,課程是「呼叫 JVM 外部並不是一個便宜的過程」?
以上是FFM(外部函數和記憶體)Stdlib 範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!