/bit/example_memory_test.go

https://code.google.com/p/go-bit/ · Go · 84 lines · 44 code · 9 blank · 31 comment · 8 complexity · 27048b0a7ffbdd4036a0cc984a96da2b MD5 · raw file

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