benchmarking


Node.js

  1. const Benchmark = require('benchmark')
  2. const suite = new Benchmark.Suite
  3. suite.add('fib#recursion', () => {
  4. fibRec(10)
  5. })
  6. .add('fib#loop', () => {
  7. fibLoop(10)
  8. })
  9. .on('complete', () => {
  10. console.log(suite[0].toString())
  11. console.log(suite[1].toString())
  12. })
  13. .run({
  14. async: true
  15. })
  16. function fibRec(n) {
  17. if (n <= 1) {
  18. return n
  19. }
  20. return fibRec(n-1) + fibRec(n-2)
  21. }
  22. function fibLoop(n) {
  23. let f = [0, 1]
  24. for (let i = 2; i <= n; i++) {
  25. f[i] = f[i-1] + f[i-2]
  26. }
  27. return f[n]
  28. }

Output

  1. $ node examples/benchmark_test.js
  2. fib#recursion x 1,343,074 ops/sec ±1.26% (84 runs sampled)
  3. fib#loop x 20,104,517 ops/sec ±3.78% (78 runs sampled)

Go

  1. package example
  2. import (
  3. "testing"
  4. )
  5. func BenchmarkFibRec(b *testing.B) {
  6. for n := 0; n < b.N; n++ {
  7. fibRec(10)
  8. }
  9. }
  10. func BenchmarkFibLoop(b *testing.B) {
  11. for n := 0; n < b.N; n++ {
  12. fibLoop(10)
  13. }
  14. }
  15. func fibRec(n int) int {
  16. if n <= 1 {
  17. return n
  18. }
  19. return fibRec(n-1) + fibRec(n-2)
  20. }
  21. func fibLoop(n int) int {
  22. f := make([]int, n+1, n+2)
  23. if n < 2 {
  24. f = f[0:2]
  25. }
  26. f[0] = 0
  27. f[1] = 1
  28. for i := 2; i <= n; i++ {
  29. f[i] = f[i-1] + f[i-2]
  30. }
  31. return f[n]
  32. }

Output

  1. $ go test -v -bench=. -benchmem examples/benchmark_test.go
  2. goos: darwin
  3. goarch: amd64
  4. BenchmarkFibRec-8 5000000 340 ns/op 0 B/op 0 allocs/op
  5. BenchmarkFibLoop-8 30000000 46.5 ns/op 96 B/op 1 allocs/op
  6. PASS
  7. ok command-line-arguments 3.502s