Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. /*
  2. The purpose of this document is to know the difference between
  3. an algorithm that uses the modulo operator vs one that does not.
  4. The two algorithms count the number of ones in the binary representation
  5. of a number.
  6.  
  7. To run the test for yourself you download the document and in the
  8. directory run the following command:
  9.  
  10. $ go test -bench=.
  11.  
  12. The results I got were the following:
  13.  
  14. $ go test -bench=.
  15. goos: linux
  16. goarch: amd64
  17. BenchmarkCount/low-numbers/modulo-4 124911303 8.92 ns/op
  18. BenchmarkCount/low-numbers/math-4 5866159 201 ns/op
  19. BenchmarkCount/high-numbers/modulo-4 15446630 70.8 ns/op
  20. BenchmarkCount/high-numbers/math-4 406203 2858 ns/op
  21. PASS
  22. ok _/tmp 5.843s
  23.  
  24. */
  25. package main
  26.  
  27. import (
  28. "math"
  29. "testing"
  30. )
  31.  
  32. func countOnesModulo(n int) int {
  33. count := 0
  34. for n > 0 {
  35. count += n % 2
  36. n = n >> 1
  37. }
  38. return count
  39. }
  40.  
  41. func countOnesMath(n int) int {
  42. count := 0
  43. num := float64(n)
  44. for num > 0 {
  45. power := math.Floor(math.Log2(num))
  46. num = num - math.Pow(2, power)
  47. count++
  48. }
  49. return count
  50. }
  51.  
  52. func TestCount(t *testing.T) {
  53. res := countOnesModulo(64)
  54. if res != 1 {
  55. t.Errorf("Modulo count failed, %d != 1", res)
  56. }
  57.  
  58. res = countOnesModulo(65)
  59. if res != 2 {
  60. t.Errorf("Modulo count failed, %d != 2", res)
  61. }
  62.  
  63. res = countOnesMath(64)
  64. if res != 1 {
  65. t.Errorf("Math count failed, %d != 1", res)
  66. }
  67.  
  68. res = countOnesMath(65)
  69. if res != 2 {
  70. t.Errorf("Math count failed, %d != 2", res)
  71. }
  72. }
  73.  
  74. func BenchmarkCount(b *testing.B) {
  75. sets := []struct {
  76. Name string
  77. Number int
  78. }{
  79. {"low-numbers", 42},
  80. {"high-numbers", 3478259823749587},
  81. }
  82.  
  83. for _, set := range sets {
  84. b.Run(set.Name, func(b *testing.B) {
  85. b.Run("modulo", func(b *testing.B) {
  86. for i := 0; i < b.N; i++ {
  87. countOnesModulo(set.Number)
  88. }
  89. })
  90.  
  91. b.Run("math", func(b *testing.B) {
  92. for i := 0; i < b.N; i++ {
  93. countOnesMath(set.Number)
  94. }
  95. })
  96. })
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement