Skip to content

Instantly share code, notes, and snippets.

@cep21
cep21 / stats.go
Last active November 15, 2016 06:54
type Stats struct {
prev runtime.MemStats
}
func (p *Stats) stats() {
ms := runtime.MemStats{}
runtime.ReadMemStats(&ms)
mallocCount := ms.Mallocs - p.prev.Mallocs
fmt.Println("malloc change is", mallocCount)
p.prev = ms
s := Stats{}
go s.Loop(ctx)
fmt.Println("I started service", s)
package main
import (
"bytes"
"fmt"
"reflect"
)
func main() {
buf := bytes.Buffer{}
my_experiment_thing profile: total 6
4 @ 0x2245 0x5d961
# 0x2244 main.usesAResource+0x64 /Users/.../pproftest.go:64
2 @ 0x2245 0x2574 0x9c184 0x9d56f 0x9df7d 0x9aa07 0x5d961
# 0x2244 main.usesAResource+0x64 /Users/.../pproftest.go:64
# 0x2573 main.main.func3+0x13 /Users/.../pproftest.go:79
# 0x9c183 net/http.HandlerFunc.ServeHTTP+0x43 /usr/local/Cellar/go/1.7.1/libexec/src/net/http/server.go:1726
# 0x9d56e net/http.(*ServeMux).ServeHTTP+0x7e /usr/local/Cellar/go/1.7.1/libexec/src/net/http/server.go:2022
# 0x9df7c net/http.serverHandler.ServeHTTP+0x7c /usr/local/Cellar/go/1.7.1/libexec/src/net/http/server.go:2202
@cep21
cep21 / pprof.go
Last active December 15, 2016 00:02
Example of how to use a custom pprof profile
package main
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"runtime/pprof"
"sync/atomic"
@cep21
cep21 / pprof_example.txt
Created December 15, 2016 00:13
pprof from console
> go tool pprof 'localhost:6060/debug/pprof/my_experiment_thing?debug=1'
Fetching profile from http://localhost:6060/debug/pprof/my_experiment_thing?debug=1
Saved profile in /Users/.../pprof/pprof.localhost:6060.my_experiment_thing.007.pb.gz
Entering interactive mode (type "help" for commands)
(pprof) top30
6 of 6 total ( 100%)
flat flat% sum% cum cum%
6 100% 100% 6 100% main.usesAResource
0 0% 100% 2 33.33% main.main.func3
0 0% 100% 2 33.33% net/http.(*ServeMux).ServeHTTP
@cep21
cep21 / abstract_example.go
Last active March 20, 2020 16:06
Example of interface wrapping erasure
package main
// Given an interface
type I interface {
Func()
}
// And another interface
type I2 interface {
Another()
@cep21
cep21 / cache_library.go
Last active July 25, 2017 22:26
example cache library
type ObjectCache {}
func (r *ObjectCache) Cached(ctx context.Context, key string, callback func() (interface{}, error), storeIntoPtr interface{}) error {
// Check cache for object, if it exists, get it from cache, otherwise call callback, store to cache, and put result
// into storeIntoPtr pointer
}
func (app * Application) UserCode(ctx context.Context) (*UserProfile, error) {
var ret *UserProfile
err := app.Cache.Cached(ctx, "user:" + userID, func() (interface{}, error) {
type I interface {
Func()
}
type I2 interface {
Another()
}
type I3 interface {
Func()
Another()
}
@cep21
cep21 / a.go
Last active August 29, 2017 22:42
Two file imports
// From package A
package a
type T int64
type S struct{}
func (s *S) TypedFunction() T {
return T(0)
}