源战役
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.6 KiB

  1. %%% -------------------------------------------------------
  2. %%% @author huangyongxing@yeah.net
  3. %%% @doc
  4. %%% 简单的性能测试工具,匿名函数的影响有限,
  5. %%% 但是方便不修改工具直接外部添加测试用例进行对比使用,
  6. %%% 所以忽略匿名函数对测试结果的影响,做基本的性能判断
  7. %%%
  8. %%% 对比测试方式:
  9. %%% ptester:run(Times, [
  10. %%% {Fun1Label, Fun1/1},
  11. %%% {Fun2Label, Fun2/1},
  12. %%% ...
  13. %%% ]).
  14. %%% 单个函数测试:
  15. %%% ptester:timer(FunLabel, Fun/1, Times).
  16. %%% @end
  17. %%% -------------------------------------------------------
  18. -module(ptester).
  19. -compile(export_all).
  20. %% 运行一个测试集
  21. run(N, List) ->
  22. [[L, T1, T2] = H | T] = [timer(Label, F, N) || {Label, F} <- List],
  23. io:format("========================================================================~n"),
  24. io:format("~20s = ~9.2fms [~8.2f%] ~9.2fms [~8.2f%]~n", [L, T1 + 0.0, 100.0, T2 + 0.0, 100.0]),
  25. compare(T, H),
  26. io:format("========================================================================~n").
  27. %% 运行单项测试并计时
  28. timer(Label, F, N) ->
  29. % WordSize = erlang:system_info(wordsize),
  30. % 分配较大的初始空间,减少gc对测试结果的影响,以期获得更准确的结果
  31. % MinHeapSize = 20 * 1024 * 1024,
  32. % MinBinVHeapSize = MinHeapSize,
  33. % erlang:process_flag(min_heap_size, MinHeapSize),
  34. % erlang:process_flag(min_bin_vheap_size, MinBinVHeapSize),
  35. % 先进行gc一次,避免多个函数测试时,上一次的测试对进程gc的相关影响
  36. erlang:garbage_collect(self()),
  37. statistics(runtime),
  38. statistics(wall_clock),
  39. for(1, N, F),
  40. {_, Time1} = statistics(runtime),
  41. {_, Time2} = statistics(wall_clock),
  42. U1 = Time1 * 1000 / N,
  43. U2 = Time2 * 1000 / N,
  44. io:format("~p [total: ~p(~p)ms avg: ~.3f(~.3f)us]~n", [Label, Time1, Time2, U1, U2]),
  45. [Label, Time1, Time2].
  46. %% 比较结果
  47. compare([], _) ->
  48. ok;
  49. compare([[L, T1, T2] | T], [_, TB1, TB2] = TB) ->
  50. io:format(
  51. "~20s = ~9.2fms [~8.2f%] ~9.2fms [~8.2f%]~n",
  52. [L, T1 + 0.0, T1 / (TB1 + 0.00000001) * 100, T2 + 0.0, T2 / (TB2 + 0.00000001) * 100]
  53. ),
  54. compare(T, TB).
  55. %% for循环
  56. for(Max, Max, F) -> F(Max);
  57. for(I, Max, F) -> F(I), for(I + 1, Max, F).
  58. %% 产生随机数
  59. rand(Same, Same) -> Same;
  60. rand(Min, Max) when Max < Min ->
  61. rand(Max, Min);
  62. rand(Min, Max) ->
  63. case get("rand_seed") of
  64. undefined ->
  65. RandSeed = os:timestamp(),
  66. rand:seed(RandSeed),
  67. put("rand_seed", RandSeed);
  68. _ ->
  69. skip
  70. end,
  71. M = Min - 1,
  72. rand:uniform(Max - M) + M.