duanhuang3074 2015-06-19 19:09
浏览 20

跑步表现

Consider the following benchmark:

package main

import (
    "io/ioutil"
    "os"
    "os/exec"
    "testing"
)

func BenchmarkRun(b *testing.B) {
    for i := 0; i < b.N; i++ {
        source := `package main

import "fmt"

func main() {
    fmt.Println("foo")
}`
        if err := ioutil.WriteFile("cmd.go", []byte(source), 0777); err != nil {
            b.Error(err)
        }
        defer os.Remove("cmd.go")

        if err := exec.Command("go", "run", "cmd.go").Run(); err != nil {
            b.Error(err)
        }
    }
}

This takes around 0.3sec per operation.

Is there any way of speeding up a compile / run cycle?

It seems clumsy to write a temporary file and exec go run. Is there a way to invoke the compiler without doing this?

  • 写回答

1条回答 默认 最新

  • duanpanyang1962 2015-06-19 20:21
    关注

    You can always create a binary and use it later on. Example:

    package main
    
    import (
            "io/ioutil"
            "os"
            "os/exec"
            "path"
            "testing"
    )
    
    func BenchmarkRun(b *testing.B) {
            tmpdir, err := ioutil.TempDir("", "go-bench-")
            if err != nil {
                    b.Fatal(err)
            }
            defer os.RemoveAll(tmpdir)
    
            source := `package main
    
    import "fmt"
    
    func main() {
        fmt.Println("foo")
    }`
            if err := ioutil.WriteFile(path.Join(tmpdir, "cmd.go"), []byte(source), 0777); err != nil {
                    b.Fatal(err)
            }
            defer os.Remove(path.Join(tmpdir, "cmd.go"))
    
            cmd := exec.Command("go", "build", "-o", "cmd", ".")
            cmd.Dir = tmpdir
            if err := cmd.Run(); err != nil {
                    b.Fatal(err)
            }
            defer os.Remove(path.Join(tmpdir, "cmd"))
    
            b.ResetTimer()
            for i := 0; i < b.N; i++ {
                    if err := exec.Command(path.Join(tmpdir, "cmd")).Run(); err != nil {
                            b.Error(err)
                    }
            }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序