- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我只是编写一些简单的实用程序来计算 linkedList 的长度,这样 linkedList 就不会托管其大小/长度的“内部”计数器。考虑到这一点,我有 3 个简单的方法:
下面是一些捕获这 3 种情况的代码:
// 1. iterative approach
public static <T> int getLengthIteratively(LinkedList<T> ll) {
int length = 0;
for (Node<T> ptr = ll.getHead(); ptr != null; ptr = ptr.getNext()) {
length++;
}
return length;
}
// 2. recursive approach
public static <T> int getLengthRecursively(LinkedList<T> ll) {
return getLengthRecursively(ll.getHead());
}
private static <T> int getLengthRecursively(Node<T> ptr) {
if (ptr == null) {
return 0;
} else {
return 1 + getLengthRecursively(ptr.getNext());
}
}
// 3. Pseudo tail-recursive approach
public static <T> int getLengthWithFakeTailRecursion(LinkedList<T> ll) {
return getLengthWithFakeTailRecursion(ll.getHead());
}
private static <T> int getLengthWithFakeTailRecursion(Node<T> ptr) {
return getLengthWithFakeTailRecursion(ptr, 0);
}
private static <T> int getLengthWithFakeTailRecursion(Node<T> ptr, int result) {
if (ptr == null) {
return result;
} else {
return getLengthWithFakeTailRecursion(ptr.getNext(), result + 1);
}
}
现在我知道 JVM 不支持开箱即用的尾递归,但是当我运行一些具有约 10k 节点的字符串 linkedList 的简单测试时,我注意到 getLengthWithFakeTailRecursion
始终优于 getLengthRecursively
方法(约 40%)。增量是否仅归因于案例#2 的控制权被传回每个节点并且我们被迫遍历所有堆栈帧这一事实?
编辑:这是我用来检查性能数字的简单测试:
public class LengthCheckerTest {
@Test
public void testLengthChecking() {
LinkedList<String> ll = new LinkedList<String>();
int sizeOfList = 12000;
// int sizeOfList = 100000; // Danger: This causes a stackOverflow in recursive methods!
for (int i = 1; i <= sizeOfList; i++) {
ll.addNode(String.valueOf(i));
}
long currTime = System.nanoTime();
Assert.assertEquals(sizeOfList, LengthChecker.getLengthIteratively(ll));
long totalTime = System.nanoTime() - currTime;
System.out.println("totalTime taken with iterative approach: " + (totalTime / 1000) + "ms");
currTime = System.nanoTime();
Assert.assertEquals(sizeOfList, LengthChecker.getLengthRecursively(ll));
totalTime = System.nanoTime() - currTime;
System.out.println("totalTime taken with recursive approach: " + (totalTime / 1000) + "ms");
// Interestingly, the fakeTailRecursion always runs faster than the vanillaRecursion
// TODO: Look into whether stack-frame collapsing has anything to do with this
currTime = System.nanoTime();
Assert.assertEquals(sizeOfList, LengthChecker.getLengthWithFakeTailRecursion(ll));
totalTime = System.nanoTime() - currTime;
System.out.println("totalTime taken with fake TCR approach: " + (totalTime / 1000) + "ms");
}
}
最佳答案
您的基准测试方法存在缺陷。您在同一个 JVM 中执行所有三个测试,因此它们的位置并不相同。当执行假尾测试时,LinkedList
和 Node
类已经经过 JIT 编译,因此运行速度更快。您可以更改测试顺序,您会看到不同的数字。每个测试都应该在单独的 JVM 中执行。
我们写简单的JMH microbenchmark对于您的情况:
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.annotations.*;
// 5 warm-up iterations, 500 ms each, then 10 measurement iterations 500 ms each
// repeat everything three times (with JVM restart)
// output average time in microseconds
@Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(3)
@State(Scope.Benchmark)
public class ListTest {
// You did not supply Node and LinkedList implementation
// but I assume they look like this
static class Node<T> {
final T value;
Node<T> next;
public Node(T val) {value = val;}
public void add(Node<T> n) {next = n;}
public Node<T> getNext() {return next;}
}
static class LinkedList<T> {
Node<T> head;
public void setHead(Node<T> h) {head = h;}
public Node<T> getHead() {return head;}
}
// Code from your question follows
// 1. iterative approach
public static <T> int getLengthIteratively(LinkedList<T> ll) {
int length = 0;
for (Node<T> ptr = ll.getHead(); ptr != null; ptr = ptr.getNext()) {
length++;
}
return length;
}
// 2. recursive approach
public static <T> int getLengthRecursively(LinkedList<T> ll) {
return getLengthRecursively(ll.getHead());
}
private static <T> int getLengthRecursively(Node<T> ptr) {
if (ptr == null) {
return 0;
} else {
return 1 + getLengthRecursively(ptr.getNext());
}
}
// 3. Pseudo tail-recursive approach
public static <T> int getLengthWithFakeTailRecursion(LinkedList<T> ll) {
return getLengthWithFakeTailRecursion(ll.getHead());
}
private static <T> int getLengthWithFakeTailRecursion(Node<T> ptr) {
return getLengthWithFakeTailRecursion(ptr, 0);
}
private static <T> int getLengthWithFakeTailRecursion(Node<T> ptr, int result) {
if (ptr == null) {
return result;
} else {
return getLengthWithFakeTailRecursion(ptr.getNext(), result + 1);
}
}
// Benchmarking code
// Measure for different list length
@Param({"10", "100", "1000", "10000"})
int n;
LinkedList<Integer> list;
@Setup
public void setup() {
list = new LinkedList<>();
Node<Integer> cur = new Node<>(0);
list.setHead(cur);
for(int i=1; i<n; i++) {
Node<Integer> next = new Node<>(i);
cur.add(next);
cur = next;
}
}
// Do not forget to return result to the caller, so it's not optimized out
@Benchmark
public int testIteratively() {
return getLengthIteratively(list);
}
@Benchmark
public int testRecursively() {
return getLengthRecursively(list);
}
@Benchmark
public int testRecursivelyFakeTail() {
return getLengthWithFakeTailRecursion(list);
}
}
这是我的机器上的结果(x64 Win7,Java 8u71)
Benchmark (n) Mode Cnt Score Error Units
ListTest.testIteratively 10 avgt 30 0,009 ± 0,001 us/op
ListTest.testIteratively 100 avgt 30 0,156 ± 0,001 us/op
ListTest.testIteratively 1000 avgt 30 2,248 ± 0,036 us/op
ListTest.testIteratively 10000 avgt 30 26,416 ± 0,590 us/op
ListTest.testRecursively 10 avgt 30 0,014 ± 0,001 us/op
ListTest.testRecursively 100 avgt 30 0,191 ± 0,003 us/op
ListTest.testRecursively 1000 avgt 30 3,599 ± 0,031 us/op
ListTest.testRecursively 10000 avgt 30 40,071 ± 0,328 us/op
ListTest.testRecursivelyFakeTail 10 avgt 30 0,015 ± 0,001 us/op
ListTest.testRecursivelyFakeTail 100 avgt 30 0,190 ± 0,002 us/op
ListTest.testRecursivelyFakeTail 1000 avgt 30 3,609 ± 0,044 us/op
ListTest.testRecursivelyFakeTail 10000 avgt 30 41,534 ± 1,186 us/op
如您所见,假尾速度与简单递归速度相同(在误差范围内),但比迭代方法慢 20-60%。所以你的结果没有被重现。
如果您实际上想要的不是稳态测量结果,而是单次测量结果(无需预热),您可以使用以下选项启动相同的基准测试:-ss -wi 0 -i 1 -f 10
。结果如下:
Benchmark (n) Mode Cnt Score Error Units
ListTest.testIteratively 10 ss 10 16,095 ± 0,831 us/op
ListTest.testIteratively 100 ss 10 19,780 ± 6,440 us/op
ListTest.testIteratively 1000 ss 10 74,316 ± 26,434 us/op
ListTest.testIteratively 10000 ss 10 366,496 ± 42,299 us/op
ListTest.testRecursively 10 ss 10 19,594 ± 7,084 us/op
ListTest.testRecursively 100 ss 10 21,973 ± 0,701 us/op
ListTest.testRecursively 1000 ss 10 165,007 ± 54,915 us/op
ListTest.testRecursively 10000 ss 10 563,739 ± 74,908 us/op
ListTest.testRecursivelyFakeTail 10 ss 10 19,454 ± 4,523 us/op
ListTest.testRecursivelyFakeTail 100 ss 10 25,518 ± 11,802 us/op
ListTest.testRecursivelyFakeTail 1000 ss 10 158,336 ± 43,646 us/op
ListTest.testRecursivelyFakeTail 10000 ss 10 755,384 ± 232,940 us/op
正如您所看到的,第一次启动比后续启动慢很多倍。而且你的结果仍然没有重现。我观察到,对于 n = 10000
,testRecursivelyFakeTail
实际上较慢(但在预热后,它达到了与 testRecursively
相同的峰值速度。
关于Java伪尾调用递归产生更好的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423375/
我在 Chrome 上做了一些测试,requestAnimationFrame 产生了 61 fps 而 setTimeOut( callback, 0 ) 产生了 233 fps。 如果一个人想要超
当我调试代码时,我发现 GCC 和 Clang 都为 0.0/0.0 产生 nan,这是我所期望的,但 GCC 产生的 nan 将符号位设置为 1,而Clang 将其设置为 0(如果我没记错的话,与
Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。 想改善这个问题吗?更新问题,以便将其作为on-topic
我在 R Studio 中有一个时间序列。现在我想计算这个系列的log()。我尝试了以下方法: i <- (x-y) ii <- log(i) 但是我得到以下信息:Warning message: I
我有兴趣了解 JavaScript 的内部结构.我试图阅读 SpiderMonkey 的来源和 Rhino但是绕过我的头是相当复杂的。 我问的原因是:为什么像 (![]+[])[+!![]+[]] 生
我们在 Delphi 中使用标准 TWebbrowser 组件,该组件在内部使用 mshtml.dll。另外,我们使用注册表来确保页面使用新的渲染引擎( Web-Browser-Control-Spe
我必须实现一个序列化/反序列化类,并且我正在使用 System.Xml.Serialization 。我有一些IList类型属性并希望在 IList 中序列化解码属于具有特定区域性信息的列表的所有十进
我有一个 Java 应用程序,它读取包含 SQL 查询的 JSON 文件,并使用 JDBC 在数据库上触发它们。 现在我有 5 万个这样的文件,我需要生成 5 万个独立线程来读取每个文件并将它们上传到
我正在尝试将 TensorFlow 入门页面上的示例线性回归程序调整为二次回归。为此,我只是添加了另一个变量并更改了函数。然而,这似乎会导致 NaN 值。这是我的代码: import numpy as
申请后KernelPCA到我的数据并将其传递给分类器 ( SVC ) 我收到以下错误: ValueError: Input contains NaN, infinity or a value too
这背后的想法是,如果我的数据库中存在登录名(正确的用户名+密码),我将重定向到一个页面,并且在进行此身份验证后,他们可以将消息存储在文本文件中。代码非常简单尽管我不确定为什么会收到 IllegalSt
我有一个返回 log10 值的函数。在将它们转换为正常数字时,出现溢出错误。 OverflowError: (34, 'Numerical result out of range') 我检查了日志值,
nosetests 抛出一个 ImportError,尽管我认为这是一个正确配置的 virtualenv。 ==============================================
我是这个网站的新手,所以如果我做错了什么,我提前道歉。当我尝试使用 kivy-garden 的 ScrollLabel 时,它给了我一个错误。基本上我正在尝试创建一个控制台日志,并且我需要能够在文本框
任何人都对 MDSJ 有任何经验?以下输入仅产生 NaN 结果,我不明白为什么。文档非常稀少。 import mdsj.Data; import mdsj.MDSJ; public class MDS
我有一个非常简单的 scala jcuda 程序,它添加了一个非常大的数组。一切都编译和运行得很好,直到我想从我的设备复制超过 4 个字节到主机。当我尝试复制超过 4 个字节时,我收到 CUDA_ER
我正在使用 Hero 组件在两个页面之间创建动画。Hero 组件用于包装一个 Image 小部件(没问题)和一个 Container 小部件(有问题)。 抛出以下溢出错误: ══╡ EXCEPTIO
我无法理解页面 https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/void 中的这一段: This ope
当在 Angular 中使用不立即触发事件的异步管道时(http 请求或任何有延迟的可观察对象),第一个值为 null为什么会这样?如何避免这种情况? 第一个变化: SimpleChange {
如果一个导入的库生成了一个会 panic 的 goroutine 怎么办?在这种情况下,开发人员无法阻止程序退出。 就像在这段代码中一样,使用延迟恢复调用一个错误的库没有帮助,因为该库正在生成一个 p
我是一名优秀的程序员,十分优秀!