File size: 985 Bytes
ca7217f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package parallel

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestParallel(t *testing.T) {
	fn := func(s string) int {
		return len(s)
	}

	for _, unit := range []struct {
		args []string
		want []int
	}{
		{
			args: []string{"a", "ab", "hello", "world"},
			want: []int{1, 2, 5, 5},
		},
		{
			args: []string{},
			want: []int{},
		},
	} {
		result := Parallel(fn, unit.args...)
		assert.Equal(t, unit.want, result)
	}
}

func mockSlowFn(x int) int {
	time.Sleep(10 * time.Millisecond)
	return x * x
}

func BenchmarkParallel(b *testing.B) {
	args := make([]int, 100)
	for i := 0; i < 100; i++ {
		args[i] = i
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		Parallel(mockSlowFn, args...)
	}
}

func BenchmarkSerial(b *testing.B) {
	args := make([]int, 100)
	for i := 0; i < 100; i++ {
		args[i] = i
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		results := make([]int, len(args))
		for j, v := range args {
			results[j] = mockSlowFn(v)
		}
	}
}