Skip to content

Instantly share code, notes, and snippets.

@dtoledom
Created January 15, 2019 18:00
Show Gist options
  • Save dtoledom/e5c3b2494e893ec97b270ea0fd4f9eed to your computer and use it in GitHub Desktop.
Save dtoledom/e5c3b2494e893ec97b270ea0fd4f9eed to your computer and use it in GitHub Desktop.
Script for running benchmark over a single endpoint in a running API
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
)
var file io.WriteCloser
var mut sync.Mutex
var results []*result
type result struct {
workerID, code, interation int
duration time.Duration
}
func reportResult(r *result) {
mut.Lock()
results = append(results, r)
file.Write([]byte(fmt.Sprintf("workerID: %d iteration: %d status: %d duration: %v\n", r.workerID, r.interation, r.code, r.duration)))
mut.Unlock()
}
func job() int {
resp, err := http.Post("http://127.0.0.1:8080/twirp/com.crabi.granTorino.Vehicle/GetBrands", "application/json", strings.NewReader("{}"))
if err != nil {
log.Println(err)
return 0
}
return resp.StatusCode
}
func startWorker(id, iterations int) {
for i := 0; i < iterations; i++ {
start := time.Now()
code := job()
duration := time.Since(start)
fmt.Printf("Worker %d: finished iteration %d\n", id, i)
reportResult(&result{
workerID: id,
code: code,
interation: i,
duration: duration,
})
}
}
func main() {
var err error
iterations := 200
concurrent := 20
results = make([]*result, 0)
file, err = os.Create("results.txt")
if err != nil {
log.Panic(err)
}
wg := &sync.WaitGroup{}
for i := 0; i < concurrent; i++ {
wg.Add(1)
go func(id int) {
startWorker(id, iterations)
wg.Done()
}(i + 1)
}
wg.Wait()
fmt.Fprintln(file)
fmt.Fprintln(file)
var averageResponse time.Duration = 0
for _, result := range results {
averageResponse += result.duration
}
averageResponse /= time.Duration(len(results))
fmt.Fprintf(file, "Average duration: %v\n", averageResponse)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment