4

reverse . sort

或者

sortBy

尝试按降序对整数列表进行排序时运行速度更快?

4

2 回答 2

8

(reverse . sort)我使用, 和进行了 Criterion 测试排序(sortBy (comparing Down))。要排序的列表是有序的和反向排序的(应该是最坏和最好的情况,不一定按那个顺序)。

代码

import Criterion
import Criterion.Main

import Data.List
import Data.Ord

main :: IO ()
main = defaultMain [ bench "Sort, forward" (whnf (reverse . sort) ([1..10000] :: [Int]))
                   , bench "Sort, backward" (whnf (reverse . sort) ([10000,9999..1] :: [Int]))
                   , bench "sortby, forward" (whnf (sortBy (comparing Down)) ([1..10000] :: [Int]))
                   , bench "sortby, backward" (whnf (sortBy (comparing Down))  ([10000,9999..1] :: [Int]))
                   ]

{-
warming up
estimating clock resolution...
mean is 2.290904 us (320001 iterations)
found 79468 outliers among 319999 samples (24.8%)
  734 (0.2%) low severe
  78734 (24.6%) high severe
estimating cost of a clock call...
mean is 512.8809 ns (23 iterations)
found 4 outliers among 23 samples (17.4%)
  2 (8.7%) high mild
  2 (8.7%) high severe

benchmarking Sort, forward
mean: 551.4973 us, lb 549.7330 us, ub 553.6538 us, ci 0.950
std dev: 9.998922 us, lb 8.400519 us, ub 12.37726 us, ci 0.950
found 4 outliers among 100 samples (4.0%)
  4 (4.0%) high mild
variance introduced by outliers: 11.316%
variance is moderately inflated by outliers

benchmarking Sort, backward
mean: 307.6627 us, lb 306.6471 us, ub 308.9350 us, ci 0.950
std dev: 5.790552 us, lb 4.777178 us, ub 7.103792 us, ci 0.950
found 9 outliers among 100 samples (9.0%)
  7 (7.0%) high mild
  2 (2.0%) high severe
variance introduced by outliers: 11.365%
variance is moderately inflated by outliers

benchmarking sortby, forward
mean: 168.2486 us, lb 167.7343 us, ub 168.8683 us, ci 0.950
std dev: 2.880548 us, lb 2.448853 us, ub 3.394461 us, ci 0.950
found 4 outliers among 100 samples (4.0%)
  4 (4.0%) high mild
variance introduced by outliers: 9.467%
variance is slightly inflated by outliers

benchmarking sortby, backward
mean: 262.6001 us, lb 261.3540 us, ub 264.1395 us, ci 0.950
std dev: 7.096662 us, lb 6.053786 us, ub 8.634885 us, ci 0.950
found 3 outliers among 100 samples (3.0%)
  3 (3.0%) high mild
variance introduced by outliers: 20.965%
variance is moderately inflated by outliers
-}

汇总结果

反转列表很昂贵。最好的情况测试reverse仍然显着(统计上)慢于最坏的情况sortBy

平均运行时间是:

  • 排序,最坏情况:552us
  • 排序,最佳情况:308us
  • sortBy,最坏情况:263us
  • sortBy,最佳情况:168us
于 2013-10-02T19:59:36.463 回答
1

reverse . sort

或者

sortBy

尝试按降序对整数列表进行排序时运行速度更快?

sortBy会更快。inreverse遍历整个列表,所以reverse . sort会遍历整个列表两次。事实上,另一个答案的基准非常接近恰好是 的两倍reverse . sort!如果您使用sortBy,您只需翻转比较测试,因此在所有情况下都是首选。

于 2017-09-09T06:38:27.157 回答