Golang内存分配测试

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

Golang memory allocation test

问题

我正在尝试使用我的“程序”分配内存 - 只是为了分配内存并保留在那里 - 用于测试目的。当我在我的Mac上运行它时,活动监视器显示它分配了1.6 GB的内存,但当我将其编译为Linux并在那里运行时,它什么也不做 - 它打印出消息,但机器上的内存没有被使用。我做错了吗?有更好的方法吗?这是我的代码:

package main

import (
	"fmt"
	"unsafe"
	"time"
)

func main() {
	var buffer [100 * 1024 * 1024]string
	fmt.Printf("缓冲区的大小为:%d 字节\n", unsafe.Sizeof(buffer))
	time.Sleep(300 * time.Second)
}

起初我使用了字节作为数组类型,但即使在我的Mac上也无法正常工作。

英文:

I'm trying to allocate memory with my "program" - just to allocate it and stay there - for testing purposes. When I run it on my MacOS the Activity Monitor shows it allocates 1.6 gb, when I compile it for linux and run it there it does nothing - it prints the message but the ram isn't being used on the machine. Am I doing it wrong? Is there a better way? Here is my code:

package main


import (
	"fmt"
	"unsafe"
	"time"
)


func main() {
	var buffer [100 * 1024 * 1024]string
	fmt.Printf("The size of the buffer is: %d bytes\n", unsafe.Sizeof(buffer))
	time.Sleep(300 * time.Second)
}

First I used byte for my array type, but it did not worked event on my mac?

答案1

得分: 5

你的代码中没有任何需要内存的部分。编译器完全有权利优化整个分配过程,即使编译器没有这样做,操作系统也不会分配内存——因为你从未分配任何内容,所以很可能只是镜像了一个零页。

我对你使用的Linux和MacOS之间的微妙差异一无所知,所以很难确定。很可能你在Linux机器上检查内存只显示已分配的内存,而在MacOS上显示的是所有虚拟内存,或者可能存在其他微妙差异。无论如何,自从编译器变得聪明以及PC上有了虚拟内存以来,要得到有意义的基准测试越来越困难——我们使用的工具通常足够聪明,避免不必要的浪费;而你尝试的大多数基准测试几乎完全是不必要的浪费。

基准测试很困难。

英文:

There's nothing whatsoever in your code that requires memory. The compiler is perfectly within its rights to optimize the whole allocation away, and even if the compiler doesn't do it, the OS will not commit the memory - you're never assigning anything, so it's likely just mirroring a zero-page.

I don't know anything about the subtle differences between whatever Linux you're using and whatever MacOS you're using, so there's little that can be said with certainty. It might very well be that your way of checking memory on your linux machine gives you only committed memory, while you're seeing all virtual memory on your MacOS, or there might be other subtle differences. In any case, since compilers became smart and since we had virtual memory on PCs, it's been getting harder and harder to get any meaningful benchmarks - the tools we work with are usually smart enough to avoid unnecessary waste; and most benchmarks you'll try are pretty much completely unnecessary waste.

Benchmarking is hard.

huangapple
  • 本文由 发表于 2015年9月21日 19:14:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/32693799.html
匿名

发表评论

匿名网友

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

确定