Shailesh Yadav
Shailesh Yadav

Reputation: 301

concurrency in go -Taking same time with different no of CPU

I am running a go concurrent program with the below two case and observed that It is taking same time irrespective of no of CPU it using while execution.

Case1: When cpuUsed = 1

program took 3m20.973185s.

when I am increasing the no of CPU used.

Case2: when cpuUsed = 8

program took 3m20.9330516s. 

Please find the below Go code for more details.

package main

import (
    "fmt"
    "math/rand"
    "runtime"
    "sync"
    "time"
)

var waitG sync.WaitGroup
var cpuUsed = 1
var maxRandomNums = 1000


func init() {
    maxCPU := runtime.NumCPU() //It'll give us the max CPU :)

    cpuUsed = 8 //getting same time taken for 1 and 8
    runtime.GOMAXPROCS(cpuUsed)

    fmt.Printf("Number of CPUs (Total=%d - Used=%d) \n", maxCPU, cpuUsed)
}

func main() {

    start := time.Now()
    ids := []string{"rotine1", "routine2", "routine3", "routine4"}

    waitG.Add(4)
    for i := range ids {
        go numbers(ids[i])
    }
    waitG.Wait()

    elapsed := time.Since(start)
    fmt.Printf("\nprogram took %s. \n", elapsed)
}

func numbers(id string) {
    rand.Seed(time.Now().UnixNano())
    for i := 1; i <= maxRandomNums; i++ {
        time.Sleep(200 * time.Millisecond)
        fmt.Printf("%s-%d  ", id, rand.Intn(20)+20) 

    }
    waitG.Done()
}

Upvotes: 0

Views: 210

Answers (1)

zhlicen
zhlicen

Reputation: 346

you will find out:

total time (3 min 20s) = 200s = sleep(200ms) * loops(1000)

Let's simplify your code and focus on CPU usage:

  1. Remove the Sleep, which does not use the CPU at all
  2. fmt.Println as a stdio, does not use the CPU
  3. Random number did nothing but introduce uncertainty into the program, remove it
  4. The only code that takes CPU in the goroutine is the "rand.Intn(20)+20", making it a constant addition
  5. Increase the "maxRandomNums"

then your code will be like this, run it again

package main

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

var waitG sync.WaitGroup
var cpuUsed = 1
var maxRandomNums = 1000000000

func init() {
    maxCPU := runtime.NumCPU() //It'll give us the max CPU :)

    cpuUsed = 8 //getting same time taken for 1 and 8
    runtime.GOMAXPROCS(cpuUsed)

    fmt.Printf("Number of CPUs (Total=%d - Used=%d) \n", maxCPU, cpuUsed)
}

func main() {

    start := time.Now()
    ids := []string{"rotine1", "routine2", "routine3", "routine4"}

    waitG.Add(4)
    for i := range ids {
        go numbers(ids[i])
    }
    waitG.Wait()

    elapsed := time.Since(start)
    fmt.Printf("\nprogram took %s. \n", elapsed)
}

func numbers(id string) {
    // rand.Seed(time.Now().UnixNano())
    for i := 1; i <= maxRandomNums; i++ {
        // time.Sleep(200 * time.Millisecond)
        // fmt.Printf("%s-%d  ", id, rand.Intn(20)+20)
        _ = i + 20

    }
    waitG.Done()
}

Upvotes: 1

Related Questions