3 // Copyright 2014 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
8 // fibo <n> compute fibonacci(n), n must be >= 0
9 // fibo -bench benchmark fibonacci computation (takes about 1 min)
12 // -half add values using two half-digit additions
13 // -opt optimize memory allocation through reuse
14 // -short only print the first 10 digits of very large fibonacci numbers
16 // Command fibo is a stand-alone test and benchmark to
17 // evaluate the performance of bignum arithmetic written
24 "math/big" // only used for printing
33 bench = flag.Bool("bench", false, "run benchmarks")
34 half = flag.Bool("half", false, "use half-digit addition")
35 opt = flag.Bool("opt", false, "optimize memory usage")
36 short = flag.Bool("short", false, "only print first 10 digits of result")
39 // A large natural number is represented by a nat, each "digit" is
40 // a big.Word; the value zero corresponds to the empty nat slice.
43 const W = 1 << (5 + ^big.Word(0)>>63) // big.Word size in bits
45 // The following methods are extracted from math/big to make this a
46 // stand-alone program that can easily be run without dependencies
47 // and compiled with different compilers.
49 func (z nat) make(n int) nat {
51 return z[:n] // reuse z
53 // Choosing a good value for e has significant performance impact
54 // because it increases the chance that a value can be reused.
55 const e = 4 // extra capacity
56 return make(nat, n, n+e)
60 func (z nat) set(x nat) nat {
67 // (like add, but operating on half-digits at a time)
68 func (z nat) halfAdd(x, y nat) nat {
76 // n == 0 because m >= n; result is 0
84 const W2 = W / 2 // half-digit size in bits
85 const M2 = (1 << W2) - 1 // lower half-digit mask
89 for i := 0; i < n; i++ {
91 c += x[i]&M2 + y[i]&M2
95 c += x[i]>>W2 + y[i]>>W2
99 for i := n; i < m; i++ {
117 func (z nat) add(x, y nat) nat {
125 // n == 0 because m >= n; result is 0
136 for i, xi := range x[:n] {
140 // see "Hacker's Delight", section 2-12 (overflow detection)
141 c = ((xi & yi) | ((xi | yi) &^ zi)) >> (W - 1)
143 for i, xi := range x[n:] {
146 c = (xi &^ zi) >> (W - 1)
148 copy(z[n+i+1:], x[i+1:])
159 func bitlen(x big.Word) int {
168 func (x nat) bitlen() int {
169 if i := len(x); i > 0 {
170 return (i-1)*W + bitlen(x[i-1])
175 func (x nat) String() string {
177 s := new(big.Int).SetBits(x).String()
178 if *short && len(s) > shortLen {
179 s = s[:shortLen] + "..."
184 func fibo(n int, half, opt bool) nat {
195 var f2 nat // reuse f2
196 for i := 1; i < n; i++ {
197 f2 = f2.halfAdd(f1, f0)
198 f0, f1, f2 = f1, f2, f0
201 for i := 1; i < n; i++ {
202 f2 := nat(nil).halfAdd(f1, f0) // allocate a new f2 each time
208 var f2 nat // reuse f2
209 for i := 1; i < n; i++ {
211 f0, f1, f2 = f1, f2, f0
214 for i := 1; i < n; i++ {
215 f2 := nat(nil).add(f1, f0) // allocate a new f2 each time
220 return f1 // was f2 before shuffle
223 var tests = []struct {
238 {100, "354224848179261915075"},
239 {1000, "43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875"},
242 func test(half, opt bool) {
243 for _, test := range tests {
244 got := fibo(test.n, half, opt).String()
245 if got != test.want {
246 fmt.Printf("error: got std fibo(%d) = %s; want %s\n", test.n, got, test.want)
253 if W != 32 && W != 64 {
254 fmt.Printf("error: unexpected wordsize %d", W)
257 for i := 0; i < 4; i++ {
258 test(i&2 == 0, i&1 != 0)
264 f := fibo(n, *half, *opt)
265 t := time.Since(start)
266 fmt.Printf("fibo(%d) = %s (%d bits, %s)\n", n, f, f.bitlen(), t)
269 func benchFibo(b *testing.B, n int, half, opt bool) {
270 for i := 0; i < b.N; i++ {
275 func doBench(half, opt bool) {
276 w := tabwriter.NewWriter(os.Stdout, 0, 8, 2, ' ', tabwriter.AlignRight)
277 fmt.Fprintf(w, "wordsize = %d, half = %v, opt = %v\n", W, half, opt)
278 fmt.Fprintf(w, "n\talloc count\talloc bytes\tns/op\ttime/op\t\n")
279 for n := 1; n <= 1e6; n *= 10 {
280 res := testing.Benchmark(func(b *testing.B) { benchFibo(b, n, half, opt) })
281 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()))
291 if args := flag.Args(); len(args) > 0 {
293 fmt.Printf("half = %v, opt = %v, wordsize = %d bits\n", *half, *opt, W)
294 for _, arg := range args {
295 n, err := strconv.Atoi(arg)
296 if err != nil || n < 0 {
297 fmt.Println("invalid argument", arg)
306 for i := 0; i < 4; i++ {
307 doBench(i&2 == 0, i&1 != 0)