In C we have <time.h> and clock()
and CLOCKS_PER_SEC
, delivering consistent and reliable times, how to do this in Go?
评论:
mcouturier:
nasciiboy:You can use the testing package as a regular package in a regular go file... this is an example:
https://golang.org/pkg/testing/#example_B_RunParallel
EDIT: There is a function
func Benchmark(f func(b *B)) BenchmarkResult {}
that gives you aBenchmarkResult
without outputting it.
hell_0n_wheel:brilliant! promising and interesting, I'll prove it tomorrow
nasciiboy:Why are you discounting
Testing.B
?It's like you're asking "How to print to screen? (no fmt.Print)"
hell_0n_wheel:b.Log....? No, it is to make comparisons of regexps with several languages and libraries (comming son ^-^ (again...)), and the output of
test
is far from being appropriate for that work
titpetric:the output of test is far from being appropriate for that work
No idea what you're on about. The output of test is perfect for that use case.
FUZxxl:How about using the same:
//#include <time.h> import "C" import "time" var startTime = time.Now() var startTicks = C.clock() func CpuUsagePercent() float64 { clockSeconds := float64(C.clock()-startTicks) / float64(C.CLOCKS_PER_SEC) realSeconds := time.Since(startTime).Seconds() return clockSeconds / realSeconds * 100 }
Source: stackoverflow comment
titpetric:Oh no please don't. cgo has a rather large overhead, distorting your measurements.
FUZxxl:Want to give a stab at implementing it in assembly, or would it not work (ie, improve the situation)? :)
nasciiboy:No. Just use the Go API. Though I guess you could tr to read the performance counters in assembly.
SpokenSpruce:EXCELSIOR!
package main //#include <time.h> import "C" import ( "fmt" ) func main(){ init := CpuTime() // .... fmt.Printf( "CpuTime %d\n", DiffCpuTimeByMS( init, CpuTime() ) ) } func CpuTime() uint64 { return uint64(C.clock()) } func DiffCpuTimeByMS( begin, end uint64 ) uint64 { return (end - begin) * 1000 / uint64(C.CLOCKS_PER_SEC) }
compiling
$ go build main.go
nasciiboy:Not sure if this is very precise, but this is how I did that in a test just to see how much time all of the subtests took.
startTime := time.Now() // Do Stuff result := time.Since(startTime)
vietnq:time.Now(), returns system time, on the other hand, clock (C) returns an approximation of the processor time used by the program
nasciiboy:You can use time API with Go 1.9 https://tip.golang.org/pkg/time/#hdr-Monotonic_Clocks
thanks for the info. I have updatedand and tested, althought the C clock() is more consistent. The official documetation... is a bit confusing
