gpt4 book ai didi

elixir - Elixir 中是否有 python 的 timeit 的等效模块?

转载 作者:行者123 更新时间:2023-12-01 09:56:21 25 4
gpt4 key购买 nike

在 python 中,您可以使用 timeit 模块对代码的小块执行时间进行计时。

https://docs.python.org/2/library/timeit.html

Elixir 中是否有等效项?

最佳答案

最简单的工具是使用 Erlang 的 :timer 模块,其中一个是 tc 变体。它以微秒为单位返回执行时间,并将函数的结果作为元组返回。给匿名函数计时,你可以这样做

{time, res} = :timer.tc fn -> :timer.sleep(1000) end
# {1000575, :ok}

{time, res} = :timer.tc(fn(ms) -> :timer.sleep(ms) end, [1000])
# {1001283, :ok}

给你可以做的模块功能计时

defmodule Sleepy do
def sleep(ms) do
:timer.sleep(ms)
end
end

{time, res} = :timer.tc(&Sleepy.sleep/1, [1000])
# {1001106, :ok}

{time, res} = :timer.tc(Sleepy, :sleep, [1000])
# {1000352, :ok}

Timex是另一种选择,它有一个更友好的 API 用于测量时间等等,但是如果您只需要计时,:timer 只需一些包装代码就足够了。

关于elixir - Elixir 中是否有 python 的 timeit 的等效模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26133720/

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