Guest User

Untitled

a guest
Oct 12th, 2025
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.09 KB | None | 0 0
  1. package cachebenches
  2.  
  3. import (
  4.     "math/rand"
  5.     "runtime"
  6.     "sort"
  7.     "sync/atomic"
  8.     "testing"
  9. )
  10.  
  11. // false sharing benchmark ----------------------------------------------------
  12.  
  13. type countersUnpadded struct {
  14.     values [8]uint64
  15. }
  16.  
  17. type paddedCounter struct {
  18.     value uint64
  19.     _     [56]byte
  20. }
  21.  
  22. type countersPadded struct {
  23.     values [8]paddedCounter
  24. }
  25.  
  26. func BenchmarkFalseSharing(b *testing.B) {
  27.     runtime.GOMAXPROCS(runtime.NumCPU())
  28.  
  29.     b.Run("with_false_sharing", func(b *testing.B) {
  30.         var c countersUnpadded
  31.         var goroutineID uint64
  32.  
  33.         b.ResetTimer()
  34.         b.RunParallel(func(pb *testing.PB) {
  35.             id := atomic.AddUint64(&goroutineID, 1) - 1
  36.             target := &c.values[id%uint64(len(c.values))]
  37.             for pb.Next() {
  38.                 atomic.AddUint64(target, 1)
  39.             }
  40.         })
  41.     })
  42.  
  43.     b.Run("with_padding", func(b *testing.B) {
  44.         var c countersPadded
  45.         var goroutineID uint64
  46.  
  47.         b.ResetTimer()
  48.         b.RunParallel(func(pb *testing.PB) {
  49.             id := atomic.AddUint64(&goroutineID, 1) - 1
  50.             target := &c.values[id%uint64(len(c.values))].value
  51.             for pb.Next() {
  52.                 atomic.AddUint64(target, 1)
  53.             }
  54.         })
  55.     })
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment