如何计算程序的内存大小?
假设我有一个 ac 程序,其中仅使用堆栈变量,没有动态变量(malloc,...)
是否可以计算我的程序在运行时将占用多少内存?
Lets say I have a c program where I use only stack variables, no dynamic variables (malloc, ...)
Is it possible to calculate how much memory my program will take during run time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它不仅取决于此处所述的操作系统和编译器。
一般情况下根本不可能提前确定。
例如,如果您使用递归调用,则必须知道这些调用的参数,并且如果某些参数依赖于用户输入或其他不可预测的事物,则最终会导致非常复杂的计算,而无法提前进行计算。
当然,您可以做出一些最坏的情况,但通常大多数问题的上限是无限的。
因此,只有当您的程序非常简单且线性时,您才可以这样做。
It not only depends on the OS and compiler like stated here.
It is simply impossible to determine it in advance in general.
If you make use of recursion calls, for example, you would have to know the parameters of these calls and it ends up in very complicated calculations that are impossible to make in advance if some parameters rely on user input or other unpredictable things.
Of course you could make some worst case scenario but generally the upper bounds are unlimited for most problems.
So only if your program is very simple and linear you can do so.
是的,但这样做的方法取决于操作系统。您的目标平台是什么?
Yes, but the method of doing so depends on the OS. What platform are you targeting?
是的 - 根据你的编译器/操作系统,你放在堆栈上的每个对象都有一个大小(例如 int - 4 个字节,但它根据编译器和编译器以及操作系统的不同而不同) - 你可以使用 sizeof 在运行时查找你放入堆栈的内容。
最终程序的大小将是代码的大小+您创建的堆栈的大小。
(找到代码的大小比较困难,但是您可以加载程序并在任务管理器中查看它需要多少,如果您在窗口上,这应该会给您一些估计)。
我认为top会在linux上做到这一点。
Yes - According to your compiler/os each object you put on the stack has a size (int - 4 bytes for example but it defers from compiler to compiler and from os to os) - you can use sizeof to find in runtime the size of what you put on the stack.
Eventually the szie of the program will be the size of the code + the size of the stack you create.
(finding the size of the code is harder, but you can just load the program and see in task manager how much it takes, this should give you some estimation if you're on window).
I think the top will do it on linux.
如果是 Linux,例如 FC9 等,请参阅 /proc/[PID]/maps,例如:
这才有意义
If Linux such as FC9 etc, please see /proc/[PID]/maps, e.g.:
that'll make sense
它还取决于您的调用跟踪有多深。 (您是否使用递归函数等等。)此外,您的操作系统可以增加堆栈吗?
It also depends on if how deep your call trace is. (Are you using recursive functions or not and so on.) Also, can your OS grow stacks?
有一些 CPU 和内存分析工具可以帮助您了解程序在运行时占用了多少 CPU 时间或内存。
There are CPU and memory profiling tools available that help you find how much CPU time or memory your program takes at run-time.