简体   繁体   English

为什么在对象上使用new()不会包含在Go的内存配置文件中?

[英]Why does using new() on an object not get included in the memory profiling file in Go?

This is the code I am profiling: 这是我正在分析的代码:

package main

import (
    "testing"
)

type T struct {
    a int
    b int
}

func TestA(t *testing.T) {
    Add(1, 2)
}

func (t *T) Add() int {
    return t.a + t.b
}

func Add(a, b int) *T {
    t := new(T)
    t.a = a
    t.b = b
    return t
}

I ran the test using: 我使用以下命令运行测试:

go test -memprofile mem.prof abc_test.go

But I can't find any allocation in the profiling file: 但是我在性能分析文件中找不到任何分配:

$ go tool pprof --alloc_objects main.test mem.prof
File: main.test
Type: alloc_objects
Time: Jul 9, 2018 at 9:40am (UTC)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
Showing nodes accounting for 0, 0% of 0 total
  flat  flat%   sum%        cum   cum%

Is there something wrong? 有什么不对? To my understanding, the line t:= new(T) will cause an allocation. 据我了解,行t:= new(T)将导致分配。

First of all is better if you split your test and core function into two file. 首先,最好将测试功能和核心功能分成两个文件。 By that I mean in your main.go file should have 我的意思是在您的main.go文件中应该有

package main

type T struct {
    a int
    b int
}

func (t *T) Add() int {
    return t.a + t.b
}

func Add(a, b int) *T {
    t := new(T)
    t.a = a
    t.b = b
    return t
}

and main_test.go main_test.go

package main

import "testing"

func TestA(t *testing.T) {
    Add(1, 2)
}

Then to resolve your anserw. 然后解决您的回答。 Memprofiling is build into bench tool https://golang.org/pkg/runtime/pprof/ so you need to run your pprof profiling by using Memprofiling内置于bench工具https://golang.org/pkg/runtime/pprof/中,因此您需要使用以下命令运行pprof分析

go test -memprofile mem.prof -bench .

As you can see there was -bench flag missing in your command 如您所见,命令中缺少-bench标志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM