1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add TrackFuncTime in datetime package

This commit is contained in:
dudaodong
2024-09-06 15:51:56 +08:00
parent c3372e18b1
commit 5e3337a52e
5 changed files with 115 additions and 5 deletions

View File

@@ -30,6 +30,7 @@ package datetime
import (
"fmt"
"runtime"
"strings"
"time"
)
@@ -382,11 +383,31 @@ func TimestampNano(timezone ...string) int64 {
return t.UnixNano()
}
// TraceFuncTime: trace the func costed time,just call it at top of the func like `defer TraceFuncTime()()`
func TraceFuncTime() func() {
pre := time.Now()
// TrackFuncTime track the time of function execution.
// call it at top of the func like `defer TrackFuncTime(time.Now())()`
// Play: todo
func TrackFuncTime(pre time.Time) func() {
callerName := getCallerName()
return func() {
elapsed := time.Since(pre)
fmt.Println("Costs Time:\t", elapsed)
fmt.Printf("Function %s execution time:\t %v", callerName, elapsed)
}
}
func getCallerName() string {
pc, _, _, ok := runtime.Caller(2)
if !ok {
return "Unknown"
}
fn := runtime.FuncForPC(pc)
if fn == nil {
return "Unknown"
}
fullName := fn.Name()
if lastDot := strings.LastIndex(fullName, "."); lastDot != -1 {
return fullName[lastDot+1:]
}
return fullName
}

View File

@@ -408,3 +408,17 @@ func ExampleIsWeekend() {
// true
// false
}
// func ExampleTrackFuncTime() {
// defer TrackFuncTime(time.Now())()
// var n int
// for i := 0; i < 5000000; i++ {
// n++
// }
// fmt.Println(1)
// // Output:
// // 1
// }

View File

@@ -410,3 +410,12 @@ func TestTimestamp(t *testing.T) {
ts4 := TimestampNano()
t.Log(ts4)
}
func TestTrackFuncTime(t *testing.T) {
defer TrackFuncTime(time.Now())()
var n int
for i := 0; i < 5000000; i++ {
n++
}
}