Skip to content

Instantly share code, notes, and snippets.

@BenLubar
Last active December 17, 2015 15:29
Show Gist options
  • Save BenLubar/5632369 to your computer and use it in GitHub Desktop.
Save BenLubar/5632369 to your computer and use it in GitHub Desktop.
Continuously updates a file with the current timestamp. Deletes it and exits on ^C or after one million iterations.
package main
import (
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"runtime/pprof"
"strings"
"sync"
"time"
)
func main() {
{
f, err := os.Create("cpu.prof")
if err != nil {
log.Fatalf("creating cpu profile file: %v", err)
}
defer f.Close()
if err = pprof.StartCPUProfile(f); err != nil {
log.Fatalf("starting cpu profile: %v", err)
}
defer pprof.StopCPUProfile()
}
cleanup, err := http.NewRequest("DELETE", "http://localhost:8484/now", nil)
if err != nil {
log.Fatalf("constructing cleanup request: %v", err)
}
defer func() {
resp, err := http.DefaultClient.Do(cleanup)
if err != nil {
log.Fatalf("cleanup: %v", err)
}
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
quit := make(chan struct{})
{
sigint := make(chan os.Signal, 1)
go func() {
<-sigint
signal.Stop(sigint)
close(quit)
}()
signal.Notify(sigint, os.Interrupt)
}
const workers = 10
var wg sync.WaitGroup
wg.Add(workers)
for worker := 0; worker < workers; worker++ {
go func(worker int) {
defer wg.Done()
in := make(chan *http.Request, 1)
defer close(in)
out := make(chan *http.Response, 1)
go func() {
for req := range in {
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("request: %v", err)
}
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
out <- resp
}
}()
req, err := http.NewRequest("PUT", "http://localhost:8484/now", nil)
if err != nil {
log.Fatalf("constructing request: %v", err)
}
for i := worker; i < 1000000; i += workers {
select {
case <-quit:
return
default:
req.Body = ioutil.NopCloser(strings.NewReader(time.Now().Format(time.StampNano)))
in <- req
select {
case <-quit:
return
case <-out:
if i%10000 == 9999 {
log.Printf("Iteration %d", i+1)
}
}
}
}
}(worker)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment