prime_test.go
· 1.2 KiB · Go
Raw
package main
import (
"testing"
)
// ---------- 并发 Pipeline 版本 ----------
func generate() <-chan int {
ch := make(chan int)
go func() {
for i := 2; ; i++ {
ch <- i
}
}()
return ch
}
func filter(in <-chan int, prime int) <-chan int {
out := make(chan int)
go func() {
for {
i := <-in
if i%prime != 0 {
out <- i
}
}
}()
return out
}
func pipelinePrimes(n int) []int {
ch := generate()
primes := make([]int, 0, n)
for i := 0; i < n; i++ {
prime := <-ch
primes = append(primes, prime)
ch = filter(ch, prime)
}
return primes
}
// ---------- 串行版本(非并发) ----------
func isPrime(n int, primes []int) bool {
for _, p := range primes {
if n%p == 0 {
return false
}
}
return true
}
func serialPrimes(n int) []int {
primes := make([]int, 0, n)
for i := 2; len(primes) < n; i++ {
if isPrime(i, primes) {
primes = append(primes, i)
}
}
return primes
}
// ---------- 基准测试部分 ----------
const numPrimes = 1000 // 你可以调成 10、100、1000、10000 看差异
func BenchmarkPipelinePrimes(b *testing.B) {
for i := 0; i < b.N; i++ {
pipelinePrimes(numPrimes)
}
}
func BenchmarkSerialPrimes(b *testing.B) {
for i := 0; i < b.N; i++ {
serialPrimes(numPrimes)
}
}
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 | } |