liueic revised this gist . Go to revision
1 file changed, 78 insertions
prime_test.go(file created)
@@ -0,0 +1,78 @@ | |||
1 | + | package main | |
2 | + | ||
3 | + | import ( | |
4 | + | "testing" | |
5 | + | ) | |
6 | + | ||
7 | + | // ---------- 并发 Pipeline 版本 ---------- | |
8 | + | ||
9 | + | func generate() <-chan int { | |
10 | + | ch := make(chan int) | |
11 | + | go func() { | |
12 | + | for i := 2; ; i++ { | |
13 | + | ch <- i | |
14 | + | } | |
15 | + | }() | |
16 | + | return ch | |
17 | + | } | |
18 | + | ||
19 | + | func filter(in <-chan int, prime int) <-chan int { | |
20 | + | out := make(chan int) | |
21 | + | go func() { | |
22 | + | for { | |
23 | + | i := <-in | |
24 | + | if i%prime != 0 { | |
25 | + | out <- i | |
26 | + | } | |
27 | + | } | |
28 | + | }() | |
29 | + | return out | |
30 | + | } | |
31 | + | ||
32 | + | func pipelinePrimes(n int) []int { | |
33 | + | ch := generate() | |
34 | + | primes := make([]int, 0, n) | |
35 | + | for i := 0; i < n; i++ { | |
36 | + | prime := <-ch | |
37 | + | primes = append(primes, prime) | |
38 | + | ch = filter(ch, prime) | |
39 | + | } | |
40 | + | return primes | |
41 | + | } | |
42 | + | ||
43 | + | // ---------- 串行版本(非并发) ---------- | |
44 | + | ||
45 | + | func isPrime(n int, primes []int) bool { | |
46 | + | for _, p := range primes { | |
47 | + | if n%p == 0 { | |
48 | + | return false | |
49 | + | } | |
50 | + | } | |
51 | + | return true | |
52 | + | } | |
53 | + | ||
54 | + | func serialPrimes(n int) []int { | |
55 | + | primes := make([]int, 0, n) | |
56 | + | for i := 2; len(primes) < n; i++ { | |
57 | + | if isPrime(i, primes) { | |
58 | + | primes = append(primes, i) | |
59 | + | } | |
60 | + | } | |
61 | + | return primes | |
62 | + | } | |
63 | + | ||
64 | + | // ---------- 基准测试部分 ---------- | |
65 | + | ||
66 | + | const numPrimes = 1000 // 你可以调成 10、100、1000、10000 看差异 | |
67 | + | ||
68 | + | func BenchmarkPipelinePrimes(b *testing.B) { | |
69 | + | for i := 0; i < b.N; i++ { | |
70 | + | pipelinePrimes(numPrimes) | |
71 | + | } | |
72 | + | } | |
73 | + | ||
74 | + | func BenchmarkSerialPrimes(b *testing.B) { | |
75 | + | for i := 0; i < b.N; i++ { | |
76 | + | serialPrimes(numPrimes) | |
77 | + | } | |
78 | + | } |
Newer
Older