Help us understand the problem. What is going on with this article?

Elixirでパフォーマンス測定

More than 5 years have passed since last update.

概要

  • 特定の処理に何秒かかっているか測定する方法
  • :timer.tcを使って測定する
  • :timer.tc(function):timer.tc(function, arguments):timer.tc(Module, function, arguments)の3種類
  • 戻り値は{time, functionの戻り値}のタプル

コード

MapとHashDictの作成とアクセス時間の測定

defmodule Measure do
    @size_list [10, 100, 1_000, 10_000]

    def start do
        map_list = create Map
        access(map_list, Map)
        map_list = create HashDict
        access(map_list, HashDict)
    end

    def create(dict_mod) do
        IO.inspect "#{dict_mod} create"
        IO.inspect "-------------"
        res = for size <- @size_list do
            # 指定サイズのDict(Map or HashDict)を作成する無名関数
            f = fn ->
                for key <- 100_001..(100_000 + size), into: dict_mod.new do
                    # keyをatom化
                    {Integer.to_string(key) |> String.to_atom, key}
                end
            end
            # 無名関数を格納した変数をtimer.tcに渡す
            {time, dict} = :timer.tc(f)
            IO.inspect "size: #{size}"
            IO.inspect "time: #{time} μs"
            IO.inspect "-------------"
            dict
        end
        res
    end

    def access(dict_list, dict_mod) do
        IO.inspect "#{dict_mod} access"
        IO.inspect "-------------"
        for dict <- dict_list do
            size = dict_mod.size(dict)
            f = fn ->
                # Dictサイズ分ループする度にkeyの値にアクセス
                for key <- 100_001..(100_000 + size) do
                    dict_mod.get(dict, key)
                end
            end
            # 無名関数を格納した変数をtimer.tcに渡す
            {time, _} = :timer.tc(f)
            IO.inspect "size: #{size}"
            IO.inspect "time: #{time} μs"
            IO.inspect "-------------"

        end
    end
end

Measure.start

結果

  • サイズが大きくなるほどHashDictの方が作成・アクセスともに早い

Map

10 100 1_000 10_000
create 24 μs 133 μs 7677 μs 594045 μs
access 25 μs 45 μs 1973 μs 107783 μs

HashDict

10 100 1_000 10_000
create 37 μs 113 μs 1236 μs 17074 μs
access 25 μs 42 μs 1236 μs 4637 μs
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away