【问题标题】:Running functions in R multiple times during benchmarking在基准测试期间多次在 R 中运行函数
【发布时间】:2011-08-02 21:38:54
【问题描述】:

我正在尝试使用system.time() 测量 R 中函数的计算时间。 我想运行该函数几百次以获得平均值,但我不想 复制和粘贴多次。有没有更简单的方法来做到这一点?

【问题讨论】:

    标签: function r benchmarking


    【解决方案1】:

    微基准测试包采用,times= 选项,并具有更准确的额外好处。

    > library(microbenchmark)
    > m <- microbenchmark( seq(10)^2, (1:10)^2, times=10000)
    > m
    Unit: nanoseconds
           expr   min    lq median    uq     max
    1  (1:10)^2  2567  3423   3423  4278   41918
    2 seq(10)^2 44484 46195  46195 47051 1804147
    > plot(m)
    

    并为 ggplot2 使用尚未发布的 autoplot() 方法:

    autoplot(m)
    

    【讨论】:

    • 我喜欢用require(lattice); bwplot(expr~time, m, auto.key=TRUE, xlim=quantile(v$time,c(0,0.95)))require(latticeExtra); ecdfplot(~time, groups=expr, m, auto.key=TRUE, xlim=quantile(v$time,c(0,0.95))) 将它绘制成格子。
    • @Marek 我同意默认情节看起来很糟糕......当我前几天在一个实际示例中使用它时,我使用了ggplot 并做了四分位数:stackoverflow.com/questions/1296646/…
    • 请注意,上面使用的autoplot.microbenchmark 现在可以在taRifx 1.0.3 中使用,在接下来的几个小时内应该可以在 CRAN 上使用。
    【解决方案2】:
    system.time(replicate (  ... stuff ..) )
    

    或者:(嘿,我并不羞于得到与德克相同的答案。)

    require(rbenchmark)
    benchmark( stuff... )   # Nice for comparative work
    

    【讨论】:

      【解决方案3】:

      您想使用rbenchmark 包及其函数benchmark(),它几乎可以为您完成所有工作。

      这是其帮助页面中的第一个示例:

      R> example(benchmark)
      
      bnchmrR> # example 1
      bnchmrR> # benchmark the allocation of one 10^6-element numeric vector, 
      bnchmrR> # replicated 100 times
      bnchmrR> benchmark(1:10^6)
          test replications elapsed relative user.self sys.self user.child sys.child
      1 1:10^6          100   0.327        1      0.33        0          0         0
      

      对于真正的表达式级基准测试,还有microbenchmark 包。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 2013-11-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多