Skip to content

armgit / hey

Public Imported from GitHub
0

HTTP load generator, ApacheBench (ab) replacement

Go

Try to immediately use workers when they are done.

Mehmet Akin143b780846dd
diff --git a/commands/run.go b/commands/run.go
index e364289..f99ad43 100644
--- a/commands/run.go
+++ b/commands/run.go
@@ -15,11 +15,10 @@
package commands
import (
+ "github.com/cheggaaa/pb"
"net/http"
"sync"
"time"
-
- "github.com/cheggaaa/pb"
)
func (b *Boom) Run() {
@@ -47,41 +46,47 @@ func (b *Boom) teardown() {
func (b *Boom) run() {
rem := b.N
- for {
- if rem == 0 {
- break
- }
+ if rem == 0 {
+ return
+ }
- c := b.C
- if rem < b.C {
- c = rem
- }
+ c := b.C
+ if rem < b.C {
+ c = rem
+ }
- var wg sync.WaitGroup
- wg.Add(c)
- for i := 0; i < c; i++ {
- go func() {
- b.runOneReq()
- b.bar.Increment()
- wg.Done()
- }()
- }
- wg.Wait()
- rem -= c
+ wg := new(sync.WaitGroup)
+ ch := make(chan *http.Request)
+ // Create c amount worker goroutines.
+ for i := 0; i < c; i++ {
+ wg.Add(1)
+ go b.worker(ch, wg)
+ }
+ // Push requests to channel.
+ for i := 0; i < rem; i++ {
+ ch <- b.Req
}
+ close(ch)
+ // Wait all goroutines to finish.
+ wg.Wait()
}
-func (b *Boom) runOneReq() {
- s := time.Now()
- resp, err := b.Client.Do(b.Req)
+func (b *Boom) worker(clientChan chan *http.Request, wg *sync.WaitGroup) {
+ defer wg.Done()
- code := 0
- if resp != nil {
- code = resp.StatusCode
- }
- b.results <- &result{
- statusCode: code,
- duration: time.Now().Sub(s),
- err: err,
+ for req := range clientChan {
+ s := time.Now()
+ resp, err := b.Client.Do(req)
+
+ code := 0
+ if resp != nil {
+ code = resp.StatusCode
+ }
+ b.results <- &result{
+ statusCode: code,
+ duration: time.Now().Sub(s),
+ err: err,
+ }
+ b.bar.Increment()
}
}