Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fgm/c158c593e99633b86ea1 to your computer and use it in GitHub Desktop.
Save fgm/c158c593e99633b86ea1 to your computer and use it in GitHub Desktop.
// A solution to https://www.freelancer.com/projects/Google-Go/downloads-the-contents-com-Sees.html
package main
import (
"container/list"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"unicode/utf8"
)
// TimeEvent logs a time and an associated label.
type TimeEvent struct {
Time time.Time
Label string
}
// MakeTime is a TimeEvent Factory, using the current time and a specified label.
func MakeTime(label string) TimeEvent {
t := TimeEvent{
Time: time.Now(),
Label: label,
}
return t
}
// Output a formatted table of total and inter-event timings, with labels.
func dumpLaps(l *list.List) {
var item *list.Element = l.Front()
var headTime = item.Value.(TimeEvent).Time
var prevTime time.Time = item.Value.(TimeEvent).Time
// Skip list head
// item = item.Next()
fmt.Printf("Time ms Lap ms Event\n")
for item != nil {
value := item.Value.(TimeEvent)
fmt.Printf("%5.0fms %5.0fms %s\n", value.Time.Sub(headTime).Seconds()*1000,
value.Time.Sub(prevTime).Seconds()*1000, value.Label)
prevTime = value.Time
item = item.Next()
}
}
// Compute the time difference in seconds between the first and last TimeEvent in a list.
func totalTime(l *list.List) float64 {
var t0, t1 time.Time
t0 = l.Front().Value.(TimeEvent).Time
t1 = l.Back().Value.(TimeEvent).Time
ret := t1.Sub(t0).Seconds()
return ret
}
// Measure the length of the body of a given URL and the time taken to fetch it.
func main() {
if len(os.Args) != 2 {
log.Fatalf("Syntax: oo <absolute url>, like oo http://example.com\n")
}
url := os.Args[1]
laps := list.New()
laps.PushBack(MakeTime("Start"))
resp, err := http.Get(url)
if err != nil {
log.Fatalf("Fatal error loading site: %+v\n", err)
}
defer resp.Body.Close()
laps.PushBack(MakeTime("GET"))
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Fatal error reading body: %+v\n", err)
}
laps.PushBack(MakeTime("Read"))
fmt.Printf("Body %d runes, %d bytes, %d bytes/sec.\n\n", len(body), utf8.RuneCount(body),
int(float64(len(body))/totalTime(laps)))
dumpLaps(laps)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment