Skip to content

Instantly share code, notes, and snippets.

@praveen4g0
Created July 19, 2021 06:45
Show Gist options
  • Save praveen4g0/968d362d4136595538669844f18d014e to your computer and use it in GitHub Desktop.
Save praveen4g0/968d362d4136595538669844f18d014e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"math"
"os"
"sync"
"time"
)
type Pifunc func(int) float64
func wraplogger(fun Pifunc, logger *log.Logger) Pifunc {
return func(n int) float64 {
fn := func(n int) (result float64) {
defer func(t time.Time) {
logger.Printf("took=%v, n=%v, result=%v", time.Since(t), n, result)
}(time.Now())
return fun(n)
}
return fn(n)
}
}
func wrapcache(fun Pifunc, cache *sync.Map) Pifunc {
return func(n int) float64 {
fn := func(n int) float64 {
key := fmt.Sprintf("n=%d", n)
val, ok := cache.Load(key)
if ok {
return val.(float64)
}
r := fun(n)
cache.Store(key, r)
return r
}
return fn(n)
}
}
func Pi(n int) float64 {
ch := make(chan float64)
for i := 0; i <= n; i++ {
go func(ch chan float64, i float64) {
ch <- 4 * math.Pow(-1, i) / (2*i + 1)
}(ch, float64(i))
}
result := 0.0
for i := 0; i <= n; i++ {
result += <-ch
}
return result
}
func Divide(n int) float64 {
return float64(n / 2)
}
func main() {
p := wrapcache(Pi, &sync.Map{})
g := wraplogger(p, log.New(os.Stdout, "Pi ", 1))
g(100000)
g(20000)
g(100000)
d := wrapcache(Divide, &sync.Map{})
dw := wraplogger(d, log.New(os.Stdout, "Divide ", 1))
dw(1000)
dw(55555)
dw(55555)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment