测试内存消耗

huangapple go评论215阅读模式
英文:

Test memory consumption

问题

我需要验证特定函数在执行过程中消耗的内存量,并确保它保持在特定的限制之下。

理想情况下,我希望在测试或基准测试中进行这个操作。据我所知,唯一的方法是创建一个单独的测试二进制文件,并使用BenchmarkResult来进行测试,示例如下:

func Benchmark(f func(b *B)) BenchmarkResult

这样做是正确的吗?

英文:

I need to verify how much memory a specific function consumes during execution, and make sure that it stays under a specific limit.

Ideally I'd like to do this in a test or benchmark. As far as I can see the only way to do this is to create a separate test binary and use the BenchmarkResult from

func Benchmark(f func(b *B)) BenchmarkResult

Is this the correct way to do this?

答案1

得分: 20

这不是你使用testing包的正确方式。只需创建一个名为something_test.go的文件,并编写一个名为func BenchmarkSomething(b *testing.B)的函数,然后你就可以开始了。

testing包的文档提供了更详细的说明,但基本上在编写完你的_test.go文件后,只需运行它们,启用基准测试,并针对你的问题打开-benchmem选项:

go test -bench=. -benchmem

这样就能得到你想要的结果。

英文:

That's not really how you use the testing package. Just create a file called something_test.go and write a function called func BenchmarkSomething(b *testing.B) and you're good to go.

The documentation of the testing package goes into a lot more detail, but basically after you write your _test.go files, you just run them, enable benchmarks, and specific to your question, turn on -benchmem:

go test -bench=. -benchmem

That should give you what you're looking for.

答案2

得分: 9

实际上很简单:

  1. 使用runtime.ReadMemStats(&m)memstats读入m
  2. 调用f()
  3. 再次将memstats读入m2
  4. 计算mm2之间的差异

例如:

var m1, m2 runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&m1)
f()
runtime.ReadMemStats(&m2)
fmt.Println("总内存分配:", m2.TotalAlloc - m1.TotalAlloc)
fmt.Println("mallocs次数:", m2.Mallocs - m1.Mallocs)
英文:

Actually it's very simple:

  1. Read memstats with runtime.ReadMemStats(&m) into m
  2. Invoke f()
  3. Read memstats again into m2
  4. Calculate diff between m and m2

For example:

var m1, m2 runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&m1)
f()
runtime.ReadMemStats(&m2)
fmt.Println("total:", m2.TotalAlloc - m1.TotalAlloc)
fmt.Println("mallocs:", m2.Mallocs - m1.Mallocs)

huangapple
  • 本文由 发表于 2013年12月7日 07:24:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/20435382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定