gpt4 book ai didi

profiling - 功能语言的简单时序分析器

转载 作者:行者123 更新时间:2023-12-01 14:30:02 25 4
gpt4 key购买 nike

我需要一个简单的时间分析器来估计我程序某些部分的运行时间(用 OCaml 编写,但我相信这可以适用于其他函数式语言),但我找不到一个非常简单的解决方案,类似于什么可以使用命令式语言编写代码,使用 timer.start/timer.stop 等函数。所以我尝试了一种使用惰性求值的方法,它可以很好地满足我的需要,但是我没有找到任何对这种方法的引用,所以我想知道这种方法是否有缺陷,或者是否有更简单的解决方案。

所以,问题是:你知道函数式语言(尤其是 OCaml)的类似实现吗?如果是这样,请向我指出他们,我想借用他们的一些想法来改进我的“穷人的侧写器”(我见过 this question 但它对我没有太大帮助)。据我所知,GHC 已经有一种收集时间信息的方法,所以这对 Haskell 来说可能不是问题。

顺便说一下,我尝试按照 OCaml 手册 (17.4) 中的指示进行时序分析,但它对于我需要的东西来说太“低级”了:它在 C 函数级别提供了大量信息,这使得它更难准确地评估 OCaml 代码的哪一部分是罪魁祸首。

下面是我在 OCaml 中的实现(请注意,每次我想测量时间时都需要添加“惰性”表达式,但同时我可以很好地控制我需要多少信息)。

open Unix (* for the timers *)

(** 'timers' associates keys (strings) to time counters,
to allow for multiple simultaneous measurements. *)
let timers : (string, (float * float)) Hashtbl.t = Hashtbl.create 1

(** starts the timer associated with key <name> *)
let timer_start (name : string) : unit =
let now = Unix.times () in
Hashtbl.replace timers name (now.tms_utime, now.tms_stime)

(** Returns time elapsed between the corresponding call to
timer_start and this call *)
let timer_stop (name : string) : float =
try
let now = Unix.times () in
let t = Hashtbl.find timers name in
(now.tms_utime -. fst t) +. (now.tms_stime -. snd t)
with
Not_found -> 0.0

(** Wrapper for the timer function using lazy evaluation *)
let time (s : string) (e : 'a Lazy.t) : 'a =
timer_start s;
let a = Lazy.force e in
let t2 = timer_stop s in
(* outputs timing information *)
Printf.printf "TIMER,%s,%f\n" s t2; a


(** Example *)
let rec fibo n =
match n with
| 0 -> 1
| 1 -> 1
| n' -> fibo (n - 1) + fibo (n - 2)

let main =
let f = time "fibo" (lazy (fibo 42)) in
Printf.printf "f = %d\n" f

最佳答案

Unix.times 测量 CPU 时间,而不是挂钟时间。所以这只适用于所有时间都花在 CPU 上的计算代码。顺便说一句,不需要 hashtbl,即使对于多个同时测量,也只需在 timer_start 中返回开始时间并在 timer_stop 中减去它。

关于profiling - 功能语言的简单时序分析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11958988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com