zoukankan      html  css  js  c++  java
  • golang 做了个mutex与atomic性能测试

    复制代码
    func BenchmarkMutex(b *testing.B)  {
        var number int
        lock := sync.Mutex{}
        for i:=0; i< b.N;i++{
            go func() {
                defer lock.Unlock()
                lock.Lock()
                number++
            }()
        }
    }
    
    func BenchmarkAtomic(b *testing.B)  {
        var number int32
        for i:=0; i< b.N;i++{
            go func() {
                atomic.AddInt32(&number, 1)
            }()
        }
    }
    复制代码

    用两个函数做性能测试 benchmarkMutex与benchmarkAtomic 来比较互斥锁的差异

    复制代码
    $ go test -v -cpu 1,2,4 -benchmem   -bench=. 
    goos: darwin
    goarch: amd64
    pkg: puzzlers/article21/q3
    BenchmarkMutex           1000000              2949 ns/op             424 B/op          0 allocs/op
    BenchmarkMutex-2         5000000               336 ns/op              22 B/op          0 allocs/op
    BenchmarkMutex-4        10000000               205 ns/op               0 B/op          0 allocs/op
    BenchmarkAtomic          2000000              1745 ns/op             156 B/op          0 allocs/op
    BenchmarkAtomic-2       10000000               176 ns/op               0 B/op          0 allocs/op
    BenchmarkAtomic-4       10000000               225 ns/op               0 B/op          0 allocs/op
    PASS
    ok      puzzlers/article21/q3   26.179s
    复制代码

    我们发现原子锁的性能高于互斥锁 不管从内存消耗与CPU运行 都比互斥锁要好

  • 相关阅读:
    tkinter_战队数据查询系统
    python_tkinter组件
    python_tkinter基本属性
    python_tkinter组件摆放方式
    python_推导式
    python_装饰器
    python_模块1
    python_生成随机验证码
    linux基础_使用指令3
    linux部署django项目流程(全)
  • 原文地址:https://www.cnblogs.com/ExMan/p/12622096.html
Copyright © 2011-2022 走看看