4

我需要对里面的一些代码进行基准测试IO,标准很好地支持了这一点。但我想执行一些初始化步骤(每个基准测试都不同)。天真的方法:

main = defaultMain
  [ bench "the first" $ do
      initTheFirst
      theFirst
      cleanUpTheFirst
  , bench "the second" $ do
      initTheSecond
      theSecond
      cleanUpTheSecond
  ]

但它会为每次基准测试运行(默认为 100 次)执行初始化和清理,并包括初始化时间到最终结果。是否可以排除初始化时间?

补充:代码使用全局状态(实际上是mongodb),所以我不能同时准备两个初始状态。

4

2 回答 2

5

这是 argiopeweb 建议的使用自定义 main 的解决方案:

import Control.Monad
import Control.Monad.IO.Class
import Control.Concurrent
import Criterion
import Criterion.Config
import Criterion.Monad
import Criterion.Environment

main :: IO ()
main = myMain [
  (initTheFirst, theFirst),
  (initTheSecond, theSecond)
  ]

initTheFirst :: IO ()
initTheFirst = do
  putStrLn "initializing the first"
  threadDelay 1000000

theFirst :: Benchmark
theFirst = bench "the first" $ do
  return () :: IO ()

initTheSecond :: IO ()
initTheSecond = do
  putStrLn "initializing the second"
  threadDelay 1000000

theSecond :: Benchmark
theSecond = bench "the second" $ do
  return () :: IO ()

myMain :: [(IO (), Benchmark)] -> IO ()
myMain benchmarks = withConfig defaultConfig $ do
  env <- measureEnvironment
  forM_ benchmarks $ \(initialize, benchmark) -> do
    liftIO $ initialize
    runAndAnalyse (const True) env benchmark

输出:

warming up
estimating clock resolution...
mean is 1.723574 us (320001 iterations)
found 1888 outliers among 319999 samples (0.6%)
  1321 (0.4%) high severe
estimating cost of a clock call...
mean is 43.45580 ns (13 iterations)
found 2 outliers among 13 samples (15.4%)
  2 (15.4%) high severe
initializing the first

benchmarking the first
mean: 7.782388 ns, lb 7.776217 ns, ub 7.790563 ns, ci 0.950
std dev: 36.01493 ps, lb 29.29834 ps, ub 52.51021 ps, ci 0.950
initializing the second

benchmarking the second
mean: 7.778543 ns, lb 7.773192 ns, ub 7.784518 ns, ci 0.950
std dev: 28.85100 ps, lb 25.59891 ps, ub 32.85481 ps, ci 0.950

您可以看到init*函数只被调用一次并且不会影响基准测试结果。

于 2013-10-02T19:22:04.057 回答
2

我可以在这里看到三个真实的选择。在之前和之后进行初始化和清理:

main = do
  initTheFirst
  initTheSecond

  defaultMain
    [ bench "the first" theFirst
    , bench "the second" theSecond
    ]

  cleanUpTheFirst
  cleanUpTheSecond

或者,如果这不可能,还可以对您的清理和初始化过程进行基准测试,并相应地修改您的基准测试时间。

或者,您可以放弃使用提供的defaultMain功能,而是使用 Criterion 提供的低级功能自行开发。

于 2013-10-02T15:54:33.937 回答