How to mesure execution time

package  main

import (
"time"
)

func main(){

start := time.Now()


ch := make(chan int)

go func() {
	for i := 0; i < 100; i++ {
		ch <- i
	}
}()

go chanReader(ch, "JHON")
go chanReader(ch, "DOE")


elapsed := time.Since(start)
println(elapsed)

}

func chanReader(ch chan int, name string) {
for v := range ch {
	println(v, "     FROM    ", name)
	time.Sleep(time.Millisecond * 5)
 }

}

how to mesure exection time ? i know about start := time.Now() and elapsed := time.Since(start) but if I add them, main thread will finish its execution before two chanReader will finish. I also tried to add var wg sync.WaitGroup and got a deadlock, i dont know why) i want to calculate is it better to do with fun out pattern or not

Your use of the waitgroup is probably wrong. You’ll definitively need a way to communicate a finish or done signal from the workers to the main routine. And only after receiving the signal you can take the finished time.

1 Like

You had the right idea with the WaitGroup, and I’m going to assume that you implemented it correctly. But even with the correct implementation of WaitGroup, you have to terminate the for-range loop in the chanReader() function to prevent the deadlock. If the ch channel remains opened, the for v := range ch loop will never know when to stop asking for data.

To fix this, you have close the ch channel after sending it all the data you need to send in. Here’s how I did it.

package main

import (
	"sync"
	"time"
)

var wg sync.WaitGroup

func main() {

	start := time.Now()

	ch := make(chan int)

	go func() {
		for i := 0; i < 100; i++ {
			ch <- i
		}
		// Notice how I closed the channel here.
		// This lets the receiver know there's no more data going in.
		close(ch)
	}()

	wg.Add(2)
	
	go chanReader(ch, "JOHN")
	go chanReader(ch, "DOE")

	wg.Wait()

	elapsed := time.Since(start)

	println(elapsed)
}

func chanReader(ch chan int, name string) {
	defer wg.Done()
	for v := range ch {
		println(v, "     FROM    ", name)
		time.Sleep(time.Millisecond * 5)
	}

}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.