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中文网其他相关文章!