-
-
Save coder543/8c1b9cdffdf09c19ef61322bd26d2e44 to your computer and use it in GitHub Desktop.
Go context switching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"runtime" | |
"sync" | |
"time" | |
) | |
const iterations = 50000 | |
func main() { | |
single() | |
for i := 2; i <= runtime.NumCPU(); i++ { | |
multi(i) | |
} | |
multi(runtime.NumCPU() * 4) | |
multi(runtime.NumCPU() * 16) | |
multi(runtime.NumCPU() * 32) | |
multi(runtime.NumCPU() * 64) | |
multi(runtime.NumCPU() * 256) | |
} | |
func single() { | |
single := time.Now() | |
switcher() | |
fmt.Printf("1 switcher: %.2f yields/sec\n", convertToRate(1, time.Since(single))) | |
} | |
func multi(switchers int) { | |
wg := &sync.WaitGroup{} | |
multi := time.Now() | |
for proc := 0; proc < switchers; proc++ { | |
wg.Add(1) | |
go multi_switcher(wg) | |
} | |
wg.Wait() | |
fmt.Printf("%d switchers: %.2f yields/sec\n", switchers, convertToRate(switchers, time.Since(multi))) | |
} | |
func multi_switcher(wg *sync.WaitGroup) { | |
switcher() | |
wg.Done() | |
} | |
func switcher() { | |
for i := 0; i < iterations; i++ { | |
runtime.Gosched() | |
} | |
} | |
// converts a Duration into a float representing iterations/sec | |
func convertToRate(workers int, dur time.Duration) float64 { | |
return float64(iterations*workers) / (float64(dur) / float64(time.Second)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 switcher: 14_289_797.08 yields/sec | |
2 switchers: 5_866_478.94 yields/sec | |
3 switchers: 4_832_941.33 yields/sec | |
4 switchers: 4_604_051.57 yields/sec | |
5 switchers: 4_268_906.99 yields/sec | |
6 switchers: 3_982_688.58 yields/sec | |
7 switchers: 3_799_103.41 yields/sec | |
8 switchers: 3_673_094.58 yields/sec | |
9 switchers: 3_513_868.07 yields/sec | |
10 switchers: 3_351_813.00 yields/sec | |
11 switchers: 3_325_754.64 yields/sec | |
12 switchers: 3_150_383.56 yields/sec | |
13 switchers: 3_037_539.31 yields/sec | |
14 switchers: 2_435_807.77 yields/sec | |
15 switchers: 2_326_201.72 yields/sec | |
16 switchers: 2_275_610.57 yields/sec | |
64 switchers: 2_366_303.83 yields/sec | |
256 switchers: 2_400_782.51 yields/sec | |
512 switchers: 2_408_757.26 yields/sec | |
1024 switchers: 2_418_661.29 yields/sec | |
4096 switchers: 2_460_257.29 yields/sec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment