summaryrefslogtreecommitdiff
path: root/test/fibo.go
blob: 3b816d930dfd3b44a46faead0eefc308028db4ae (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// skip

// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Usage:
// fibo <n>     compute fibonacci(n), n must be >= 0
// fibo -bench  benchmark fibonacci computation (takes about 1 min)
//
// Additional flags:
// -half        add values using two half-digit additions
// -opt         optimize memory allocation through reuse
// -short       only print the first 10 digits of very large fibonacci numbers

// Command fibo is a stand-alone test and benchmark to
// evaluate the performance of bignum arithmetic written
// entirely in Go.
package main

import (
	"flag"
	"fmt"
	"math/big" // only used for printing
	"os"
	"strconv"
	"testing"
	"text/tabwriter"
	"time"
)

var (
	bench = flag.Bool("bench", false, "run benchmarks")
	half  = flag.Bool("half", false, "use half-digit addition")
	opt   = flag.Bool("opt", false, "optimize memory usage")
	short = flag.Bool("short", false, "only print first 10 digits of result")
)

// A large natural number is represented by a nat, each "digit" is
// a big.Word; the value zero corresponds to the empty nat slice.
type nat []big.Word

const W = 1 << (5 + ^big.Word(0)>>63) // big.Word size in bits

// The following methods are extracted from math/big to make this a
// stand-alone program that can easily be run without dependencies
// and compiled with different compilers.

func (z nat) make(n int) nat {
	if n <= cap(z) {
		return z[:n] // reuse z
	}
	// Choosing a good value for e has significant performance impact
	// because it increases the chance that a value can be reused.
	const e = 4 // extra capacity
	return make(nat, n, n+e)
}

// z = x
func (z nat) set(x nat) nat {
	z = z.make(len(x))
	copy(z, x)
	return z
}

// z = x + y
// (like add, but operating on half-digits at a time)
func (z nat) halfAdd(x, y nat) nat {
	m := len(x)
	n := len(y)

	switch {
	case m < n:
		return z.add(y, x)
	case m == 0:
		// n == 0 because m >= n; result is 0
		return z.make(0)
	case n == 0:
		// result is x
		return z.set(x)
	}
	// m >= n > 0

	const W2 = W / 2         // half-digit size in bits
	const M2 = (1 << W2) - 1 // lower half-digit mask

	z = z.make(m + 1)
	var c big.Word
	for i := 0; i < n; i++ {
		// lower half-digit
		c += x[i]&M2 + y[i]&M2
		d := c & M2
		c >>= W2
		// upper half-digit
		c += x[i]>>W2 + y[i]>>W2
		z[i] = c<<W2 | d
		c >>= W2
	}
	for i := n; i < m; i++ {
		// lower half-digit
		c += x[i] & M2
		d := c & M2
		c >>= W2
		// upper half-digit
		c += x[i] >> W2
		z[i] = c<<W2 | d
		c >>= W2
	}
	if c != 0 {
		z[m] = c
		m++
	}
	return z[:m]
}

// z = x + y
func (z nat) add(x, y nat) nat {
	m := len(x)
	n := len(y)

	switch {
	case m < n:
		return z.add(y, x)
	case m == 0:
		// n == 0 because m >= n; result is 0
		return z.make(0)
	case n == 0:
		// result is x
		return z.set(x)
	}
	// m >= n > 0

	z = z.make(m + 1)
	var c big.Word

	for i, xi := range x[:n] {
		yi := y[i]
		zi := xi + yi + c
		z[i] = zi
		// see "Hacker's Delight", section 2-12 (overflow detection)
		c = ((xi & yi) | ((xi | yi) &^ zi)) >> (W - 1)
	}
	for i, xi := range x[n:] {
		zi := xi + c
		z[n+i] = zi
		c = (xi &^ zi) >> (W - 1)
		if c == 0 {
			copy(z[n+i+1:], x[i+1:])
			break
		}
	}
	if c != 0 {
		z[m] = c
		m++
	}
	return z[:m]
}

func bitlen(x big.Word) int {
	n := 0
	for x > 0 {
		x >>= 1
		n++
	}
	return n
}

func (x nat) bitlen() int {
	if i := len(x); i > 0 {
		return (i-1)*W + bitlen(x[i-1])
	}
	return 0
}

func (x nat) String() string {
	const shortLen = 10
	s := new(big.Int).SetBits(x).String()
	if *short && len(s) > shortLen {
		s = s[:shortLen] + "..."
	}
	return s
}

func fibo(n int, half, opt bool) nat {
	switch n {
	case 0:
		return nil
	case 1:
		return nat{1}
	}
	f0 := nat(nil)
	f1 := nat{1}
	if half {
		if opt {
			var f2 nat // reuse f2
			for i := 1; i < n; i++ {
				f2 = f2.halfAdd(f1, f0)
				f0, f1, f2 = f1, f2, f0
			}
		} else {
			for i := 1; i < n; i++ {
				f2 := nat(nil).halfAdd(f1, f0) // allocate a new f2 each time
				f0, f1 = f1, f2
			}
		}
	} else {
		if opt {
			var f2 nat // reuse f2
			for i := 1; i < n; i++ {
				f2 = f2.add(f1, f0)
				f0, f1, f2 = f1, f2, f0
			}
		} else {
			for i := 1; i < n; i++ {
				f2 := nat(nil).add(f1, f0) // allocate a new f2 each time
				f0, f1 = f1, f2
			}
		}
	}
	return f1 // was f2 before shuffle
}

var tests = []struct {
	n    int
	want string
}{
	{0, "0"},
	{1, "1"},
	{2, "1"},
	{3, "2"},
	{4, "3"},
	{5, "5"},
	{6, "8"},
	{7, "13"},
	{8, "21"},
	{9, "34"},
	{10, "55"},
	{100, "354224848179261915075"},
	{1000, "43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875"},
}

func test(half, opt bool) {
	for _, test := range tests {
		got := fibo(test.n, half, opt).String()
		if got != test.want {
			fmt.Printf("error: got std fibo(%d) = %s; want %s\n", test.n, got, test.want)
			os.Exit(1)
		}
	}
}

func selfTest() {
	if W != 32 && W != 64 {
		fmt.Printf("error: unexpected wordsize %d", W)
		os.Exit(1)
	}
	for i := 0; i < 4; i++ {
		test(i&2 == 0, i&1 != 0)
	}
}

func doFibo(n int) {
	start := time.Now()
	f := fibo(n, *half, *opt)
	t := time.Since(start)
	fmt.Printf("fibo(%d) = %s (%d bits, %s)\n", n, f, f.bitlen(), t)
}

func benchFibo(b *testing.B, n int, half, opt bool) {
	for i := 0; i < b.N; i++ {
		fibo(n, half, opt)
	}
}

func doBench(half, opt bool) {
	w := tabwriter.NewWriter(os.Stdout, 0, 8, 2, ' ', tabwriter.AlignRight)
	fmt.Fprintf(w, "wordsize = %d, half = %v, opt = %v\n", W, half, opt)
	fmt.Fprintf(w, "n\talloc count\talloc bytes\tns/op\ttime/op\t\n")
	for n := 1; n <= 1e6; n *= 10 {
		res := testing.Benchmark(func(b *testing.B) { benchFibo(b, n, half, opt) })
		fmt.Fprintf(w, "%d\t%d\t%d\t%d\t%s\t\n", n, res.AllocsPerOp(), res.AllocedBytesPerOp(), res.NsPerOp(), time.Duration(res.NsPerOp()))
	}
	fmt.Fprintln(w)
	w.Flush()
}

func main() {
	selfTest()
	flag.Parse()

	if args := flag.Args(); len(args) > 0 {
		// command-line use
		fmt.Printf("half = %v, opt = %v, wordsize = %d bits\n", *half, *opt, W)
		for _, arg := range args {
			n, err := strconv.Atoi(arg)
			if err != nil || n < 0 {
				fmt.Println("invalid argument", arg)
				continue
			}
			doFibo(n)
		}
		return
	}

	if *bench {
		for i := 0; i < 4; i++ {
			doBench(i&2 == 0, i&1 != 0)
		}
	}
}