New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Faster utils.FileWithLineNum #6981
Conversation
Called here https://github.com/go-gorm/gorm/blob/v1.25.9/logger/logger.go#L180 Bench code: package main
import (
"context"
"fmt"
"strings"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/utils"
)
type dlog struct{}
func (dlog) LogMode(logger.LogLevel) logger.Interface { return dlog{} }
func (dlog) Info(context.Context, string, ...any) {}
func (dlog) Warn(context.Context, string, ...any) {}
func (dlog) Error(context.Context, string, ...any) {}
func (dlog) Trace(_ context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
if strings.HasSuffix(utils.FileWithLineNum(), "main.go:34") {
panic("not same")
}
}
func main() {
db, _ := gorm.Open(mysql.Open("root@tcp(127.0.0.1:3306)"), &gorm.Config{Logger: dlog{}})
db.Exec("select 1")
for j := 0; j < 10; j++ {
benchBegin := time.Now()
for i := 0; i < 9000; i++ {
db.Exec("select 1")
}
fmt.Printf("bench: %v\n", time.Since(benchBegin).Nanoseconds())
}
} Before
After
On a long chain call, like |
if ok && (!strings.HasPrefix(file, gormSourceDir) || strings.HasSuffix(file, "_test.go")) && | ||
!strings.HasSuffix(file, ".gen.go") { | ||
return file + ":" + strconv.FormatInt(int64(line), 10) | ||
pcs := [13]uintptr{} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Origin code 15-2=13
. No breaking changes.
@@ -32,12 +32,16 @@ func sourceDir(file string) string { | |||
|
|||
// FileWithLineNum return the file name and line number of the current file | |||
func FileWithLineNum() string { | |||
// the second caller usually from gorm internal, so set i start from 2 | |||
for i := 2; i < 15; i++ { | |||
_, file, line, ok := runtime.Caller(i) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The runtime.Caller(i)
's inner is caller(skip+1)
, so we use runtime.Callers(3)
in new implement.
The CI error is not my wrong, see #6982 , curious why? |
What did this pull request do?
Faster
utils.FileWithLineNum
. Avoid callruntime.Caller
multi times.Trace log performace gained a little.