74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"runtime"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// hashTask calculates SHA-256 hashes for the given number of iterations.
|
|
func hashTask(iterations int) {
|
|
data := []byte("benchmarking-sha256")
|
|
for i := 0; i < iterations; i++ {
|
|
_ = sha256.Sum256(data)
|
|
}
|
|
}
|
|
|
|
// benchmarkSingleCore benchmarks single-core performance.
|
|
func benchmarkSingleCore(iterations int) float64 {
|
|
start := time.Now()
|
|
hashTask(iterations)
|
|
duration := time.Since(start).Seconds()
|
|
return float64(iterations) / duration // Return raw score
|
|
}
|
|
|
|
// benchmarkMultiCore benchmarks multi-core performance.
|
|
func benchmarkMultiCore(iterations int, cores int) float64 {
|
|
var wg sync.WaitGroup
|
|
wg.Add(cores)
|
|
start := time.Now()
|
|
|
|
for i := 0; i < cores; i++ {
|
|
go func() {
|
|
hashTask(iterations / cores)
|
|
wg.Done()
|
|
}()
|
|
}
|
|
|
|
wg.Wait()
|
|
duration := time.Since(start).Seconds()
|
|
return float64(iterations) / duration // Return raw score
|
|
}
|
|
|
|
// humanReadable formats numbers into human-readable units.
|
|
func humanReadable(score float64) string {
|
|
units := []string{"", "K", "M", "G", "T", "P", "E", "Z"}
|
|
i := 0
|
|
for score >= 1000 && i < len(units)-1 {
|
|
score /= 1000
|
|
i++
|
|
}
|
|
return fmt.Sprintf("%.2f %s", score, units[i])
|
|
}
|
|
|
|
func main() {
|
|
iterations := 1_000_000 // Adjust this number for longer or shorter tests
|
|
|
|
fmt.Println("Starting CPU benchmark...")
|
|
|
|
// Single-core benchmark
|
|
fmt.Println("Benchmarking single-core performance...")
|
|
singleCoreScore := benchmarkSingleCore(iterations)
|
|
fmt.Printf("Single-core score: %s hashes/sec\n", humanReadable(singleCoreScore))
|
|
|
|
// Multi-core benchmark
|
|
cores := runtime.NumCPU()
|
|
fmt.Println("Benchmarking multi-core performance...")
|
|
multiCoreScore := benchmarkMultiCore(iterations, cores)
|
|
fmt.Printf("Multi-core score: %s hashes/sec\n", humanReadable(multiCoreScore))
|
|
|
|
fmt.Println("CPU Benchmark completed.")
|
|
}
|