Created
November 25, 2020 10:13
-
-
Save bohdantrotsenko/6f6c7ee1d5345d82f5f678ebf5b23076 to your computer and use it in GitHub Desktop.
A primitive cpu test
This file contains hidden or 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" | |
"log" | |
"runtime" | |
"time" | |
"golang.org/x/crypto/scrypt" | |
) | |
const ITER = 5 | |
func workItem() { | |
_, err := scrypt.Key([]byte("password"), []byte("NaCl"), 64, 8, 16, 64) | |
if err != nil { | |
log.Fatal("Incorrect usage of scrypt()") | |
} | |
} | |
func measure(n int64) time.Duration { | |
start := time.Now() | |
for i := int64(0); i < n; i++ { | |
workItem() | |
} | |
return time.Now().Sub(start) | |
} | |
func getMax(arr []float64) float64 { | |
best := 0.0 | |
for _, el := range arr { | |
if el > best { | |
best = el | |
} | |
} | |
return best | |
} | |
func opt() int64 { | |
n := int64(1) | |
var t time.Duration | |
for { | |
fmt.Printf("%d... ", n) | |
t = measure(n) | |
if t < time.Second { | |
n = n * 2 | |
} else { | |
break | |
} | |
} | |
fmt.Println() | |
fmt.Printf("Optimal: %d cycles in %f seconds\n", n, t.Seconds()) | |
series := make([]float64, ITER) | |
series[0] = (float64(n)) / t.Seconds() | |
fmt.Printf("Rate: %f\n", series[0]) | |
for i := 1; i < ITER; i++ { | |
t = measure(n) | |
series[i] = (float64(n)) / t.Seconds() | |
fmt.Printf("Rate: %f\n", series[i]) | |
} | |
fmt.Println("---------------") | |
best := getMax(series) | |
fmt.Printf("Best: %f\n", best) | |
return n | |
} | |
func workerParallel(res chan time.Time) { | |
for { | |
workItem() | |
res <- time.Now() | |
} | |
} | |
func optParallel(n int64, coresNo int) { | |
resChan := make(chan time.Time) | |
start := time.Now() | |
target := int64(coresNo) * n | |
if target < 0 { | |
fmt.Println("CPUs is too weak for a parallel test") | |
return | |
} | |
for i := 0; i < coresNo; i++ { | |
go workerParallel(resChan) | |
} | |
var end time.Time | |
for i := int64(0); i < target; i++ { | |
end = <-resChan | |
} | |
dur_s := end.Sub(start).Seconds() | |
rate := float64(target) / dur_s | |
fmt.Printf("Parallel rate: %f (reached %d in %f seconds)\n", rate, target, dur_s) | |
} | |
func main() { | |
coresNo := runtime.GOMAXPROCS(0) | |
bestFor1Core := opt() | |
fmt.Printf("Trying on %d cores.\n", coresNo) | |
runtime.GOMAXPROCS(coresNo) | |
optParallel(bestFor1Core, coresNo) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Raspberry Pi 4