#### /bit/example_memory_test.go

Go | 84 lines | 44 code | 9 blank | 31 comment | 8 complexity | 27048b0a7ffbdd4036a0cc984a96da2b MD5 | raw file
``` 1// Copyright 2012 Stefan Nilsson
2//
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
8//
9// Unless required by applicable law or agreed to in writing, software
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
14
15package bit_test
16
17import (
18	bit "."
19	"fmt"
20	"math/rand"
21)
22
23func ExampleSet_memory() {
24	// Memory management
25	S := bit.New(100, 100000) // Make a set that occupies a few kilobyes.
26	S.RemoveMax()             // The big element is gone. Memory remains.
27	S = bit.New().Set(S)      // Give excess capacity to garbage collector.
28
29	// Memory hints and memory reuse
30	IntegerRuns(10, 5)
31
32	// Example output:
33	//
34	//      Max     Size     Runs
35	//       10        9        2    {0..2, 4..9}
36	//       20       18        2    {0, 1, 3..11, 13..19}
37	//       30       24        4    {0..3, 6..8, 10..13, 15..27}
38	//       40       32        5
39	//       50       44        5
40}
41
42// IntegerRuns(s, n) generates random sets R(i), i = 1, 2, ..., n,
43// with elements drawn from 0..i*s-1 and computes the number of runs
44// in each set. A run is a sequence of at least three integers
45// a, a+1, ..., b, such that {a..b} ⊆ S and {a-1, b+1} ∩ S = ∅.
46func IntegerRuns(start, n int) {
47	// Give a capacity hint.
48	R := bit.New(n*start - 1).Clear()
49
50	fmt.Printf("\n%8s %8s %8s\n", "Max", "Size", "Runs")
51	for i := 1; i <= n; i++ {
52		// Reuse memory from last iteration.
53		R.Clear()
54
55		// Create a random set with ~86% population.
56		max := i * start
57		for j := 2 * max; j > 0; j-- {
59		}
60
61		// Compute the number of runs.
62		runs, length, prev := 0, 0, -2
63		R.Do(func(i int) {
64			if i == prev+1 { // Continue run.
65				length++
66			} else { // Start a new run.
67				if length >= 3 {
68					runs++
69				}
70				length = 1
71			}
72			prev = i
73		})
74		if length >= 3 {
75			runs++
76		}
77		fmt.Printf("%8d %8d %8d", max, R.Size(), runs)
78		if max <= 32 {
79			fmt.Printf("%4s%v", "", R)
80		}
81		fmt.Println()
82	}
83	fmt.Println()
84}
```