此为历史版本和 IPFS 入口查阅区,回到作品页
Phanix
IPFS 指纹 这是什么

作品指纹

Golang multithread

Phanix
·
·

沒實際驗證一下沒想到差這麼多

package main

import (
    "fmt"
    "sync"
    "time"
)

func elapsedMillis(t0, t1 time.Time) float64 {
    n0, n1 := float64(t0.UnixNano()), float64(t1.UnixNano())
    return (n1 - n0) / 1e6
}
func mymap() {
    var m [10000]int
    var wg sync.WaitGroup
    wg.Add(10000)

    t0 := time.Now()
    for i := 0; i < 10000; i++ {
        go func(j int) {
            defer wg.Done()
            time.Sleep(1)
            m[j] = j
            _ = m[j] + j
        }(i)
    }
    wg.Wait()
    t1 := time.Now()
    fmt.Printf("go: %fms\n", elapsedMillis(t0, t1))

    t0 = time.Now()
    for j := 0; j < 10000; j++ {
        time.Sleep(1)
        m[j] = j
        _ = m[j] + j
    }
    t1 = time.Now()
    fmt.Printf("go: %fms\n", elapsedMillis(t0, t1))
}

Output:

go: 12.056320ms
go: 151156.967680ms

Original link: Phanix's Blog

CC BY-NC-ND 4.0 授权