/
Timing.m
executable file
·70 lines (54 loc) · 2.15 KB
/
Timing.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
(* Mathematica Package *)
(*****************************************************************************)
(*Markdown!
*)
(*****************************************************************************)
BeginPackage["MathCraftAddOn`Timing`"]
mcTiming::usage = "mcTimes[program, timingFunc, timingLimit, iterationLimit] "
Begin["`Private`"]
(*****************************************************************************)
(* ::Section:: *)
(* mcTiming *)
(*
todo:
* don't waste evaluations
*)
ClearAll[mcTiming]
Attributes[mcTiming] = {HoldAll};
Options[mcTiming] = {
"ClearSystemCacheQ" -> True
};
mcTiming[program_, timingFunc_: Timing, timingLimit_: 60, iterationLimit_: 10^5, OptionsPattern[]] := Module[
{
totalTime = 0,
totalIterationLog = 0,
(*totalTimeRes, totalIterationLogRes,*)
normalizedTimeLimit = Power[10, Floor[Log[10, timingLimit]]],
res,
totalIterations = Power[10, #] & /@ Range[0, Floor[Log[10, iterationLimit]]],
nestDepth = If[$VersionNumber < 6, 2, 1] (*< in v5 and earlier, First[Timing[expr;]] /. Second->1 yields just the number of seconds required for the evaluation of expr. *)
},
Catch[
If[
Or[
(
totalTime = Nest[
First,
totalIterationLog ++;
If[OptionValue["ClearSystemCacheQ"], ClearSystemCache[]];
timingFunc @ (Do[res = program, {#}];),
nestDepth
]
) >= normalizedTimeLimit,
# === totalIterations[[-1]]
],
Throw[{totalTime, totalIterationLog}],
Print[StringForm["ran `1` iterations for a total time of `2` seconds", totalIterations[[totalIterationLog]], ToString[SetPrecision[totalTime, 3]]]]
] & /@ totalIterations
] /. {totalTimeRes_, totalIterationLogRes_} :> (
Print[StringForm["estimating based on `1` iterations run for a total time of `2` seconds", totalIterations[[totalIterationLogRes]], ToString[SetPrecision[totalTimeRes, 3]]]];
{totalTimeRes / totalIterations[[totalIterationLogRes]], res}
)
];
End[]
EndPackage[]