Last active
June 27, 2023 06:18
-
-
Save ehfeng/bdd263e3f26de44b8a588bddaea1cf4a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"math/rand" | |
"time" | |
v8 "rogchap.com/v8go" | |
) | |
var repeats = 1000 | |
func timeTrack(start time.Time, name string) { | |
elapsed := time.Since(start) | |
log.Printf("%s took %s", name, elapsed) | |
} | |
type timingResult struct { | |
eval time.Duration | |
} | |
func v8Runner() (contextTime, functionTime, firstExecutionTime, averageExecutionTime time.Duration) { | |
start := time.Now() | |
isolate := v8.NewIsolate() | |
defer isolate.Dispose() | |
start = time.Now() | |
context := v8.NewContext(isolate) | |
contextTime = time.Since(start) | |
start = time.Now() | |
fnV, err := context.RunScript("(x, y) => x + y", "addition.js") | |
if err != nil { | |
panic(err) | |
} | |
functionTime = time.Since(start) | |
start = time.Now() | |
arg1, err := v8.NewValue(isolate, int32(rand.Intn(1000))) | |
if err != nil { | |
panic(err) | |
} | |
arg2, err := v8.NewValue(isolate, int32(rand.Intn(1000))) | |
if err != nil { | |
panic(err) | |
} | |
fn, err := fnV.AsFunction() | |
if err != nil { | |
panic(err) | |
} | |
_, err = fn.Call(context.Global(), arg1, arg2) | |
if err != nil { | |
panic(err) | |
} | |
firstExecutionTime = time.Since(start) | |
start = time.Now() | |
for i := 0; i < repeats; i++ { | |
fn.Call(context.Global(), arg1, arg2) | |
} | |
averageExecutionTime = time.Since(start) / time.Duration(repeats) | |
return | |
} | |
func main() { | |
var avgContextTime, avgFunctionTime, avgFirstExecutionTime, avgExecutionTime time.Duration | |
for i := 0; i < repeats; i++ { | |
fmt.Println("Run", i) | |
contextTime, functionTime, firstExecutionTime, executionTime := v8Runner() | |
avgContextTime += contextTime / time.Duration(repeats) | |
avgFunctionTime += functionTime / time.Duration(repeats) | |
avgFirstExecutionTime += firstExecutionTime / time.Duration(repeats) | |
avgExecutionTime += executionTime / time.Duration(repeats) | |
} | |
fmt.Println("Context:", avgContextTime, "\nFunction:", avgFunctionTime, "\nFirst execution", avgFirstExecutionTime, "\nSubsequent execution:", avgExecutionTime, "\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment