1
2
3
4
5
6
7
8
9
10
11
12
13 package big
14
15 import (
16 "flag"
17 "fmt"
18 "testing"
19 "time"
20 )
21
22 var calibrate = flag.Bool("calibrate", false, "run calibration test")
23
24
25 func measure(f func()) int64 {
26 const N = 100
27 start := time.Nanoseconds()
28 for i := N; i > 0; i-- {
29 f()
30 }
31 stop := time.Nanoseconds()
32 return (stop - start) / N
33 }
34
35 func computeThresholds() {
36 fmt.Printf("Multiplication times for varying Karatsuba thresholds\n")
37 fmt.Printf("(run repeatedly for good results)\n")
38
39
40 karatsubaThreshold = 1e9
41 Tb := measure(benchmarkMulLoad)
42 fmt.Printf("Tb = %dns\n", Tb)
43
44
45 n := 8
46 th1 := -1
47 th2 := -1
48
49 var deltaOld int64
50 for count := -1; count != 0; count-- {
51
52 karatsubaThreshold = n
53 Tk := measure(benchmarkMulLoad)
54
55
56 delta := (Tb - Tk) * 100 / Tb
57
58 fmt.Printf("n = %3d Tk = %8dns %4d%%", n, Tk, delta)
59
60
61 if Tk < Tb && th1 < 0 {
62 th1 = n
63 fmt.Print(" break-even point")
64 }
65
66
67 if 0 < delta && delta < deltaOld && th2 < 0 {
68 th2 = n
69 fmt.Print(" diminishing return")
70 }
71 deltaOld = delta
72
73 fmt.Println()
74
75
76 if th1 >= 0 && th2 >= 0 && count < 0 {
77 count = 20
78 }
79
80 n++
81 }
82 }
83
84 func TestCalibrate(t *testing.T) {
85 if *calibrate {
86 computeThresholds()
87 }
88 }