Understanding memory used by a program in bash (in

2019-08-07 16:03发布

In some programming contests, problems have a memory limit (like 64MB or 256MB). How can I understand the memory used by my program (written in C++) with bash commands? Is there any way to limit the memory used by the program? The program should terminate if it uses more memory than the limit.

3条回答
贼婆χ
2楼-- · 2019-08-07 16:32

Also, for process 1234, you could look into /proc/1234/maps or /proc/1234/smaps or run pmap 1234, all these commands display the memory map of that process of pid 1234.

Try to run cat /proc/self/maps to get an example (the memory map of the process running that cat command).

The memory map of a process is initialized by execve(2) and changed by the mmap(2) syscall (etc...)

查看更多
我想做一个坏孩纸
3楼-- · 2019-08-07 16:42

The command top will give you a list of all running processes and the current memory and swap or if you prefer the GUI you can use the System Monitor Application.

As for locking down memory usage you can always use the ulimit -v to set the maximum virtual address range for a process. This will cause malloc and its buddies to fail if they try to get more memory than that set limit.

查看更多
爷的心禁止访问
4楼-- · 2019-08-07 16:44

Depending on how much work you want to put into it you can look at getrusage(), getrlimit(), and setrlimit(). For testing purposes you can call them at the beginning of your program or perhaps set them up in a parent process and fork your contest program off as a child. Then dispense with them when you submit your program for contest consideration.

查看更多
登录 后发表回答