C ++检查可用ram? [英] C++ checking available ram?

查看:102
本文介绍了C ++检查可用ram?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中如何检查我有多少可用的RAM?



我在Windows上,但对Unix答案感兴趣, >

解决方案

Windows: GlobalMemoryStatusEx 。 MSDN页面有一个详细的C示例代码。



Linux:检查/ proc / meminfo文件(讨论



OSX:请参阅此SO线程在OSX上以编程方式确定物理内存大小



但问题不清楚。有物理内存,有虚拟内存,有一个操作系统能够将一些未使用的页面交换到磁盘/其他存储。



如果你需要写一些



如果你需要确保你的malloc()/ new []调用都没有失败,那么只要捕获适当的异常或者句柄NULL结果。另一种选择是创建自己的分配器,它在开始时获得一个大的内存块,并在那里分配较小的块。



编辑:回答注释



对WinAPI的MapViewOfFile和CreateFileMapping的调用提供了排除致命情况的错误代码。由于文件映射到与您的进程数据共享的虚拟地址空间,因此您可以检查是否有足够多的可用页面。即,如果您使用的是32位系统,则无法将整个8Gb文件一次性映射到内存(但您可以映射其较小的部分),但在64位系统上映射的可能性足以满足当前的任何需求。


In C++ how would I check how much available RAM i have?

I am on windows, but be interested for Unix answers as well as windows.

解决方案

Windows: GlobalMemoryStatusEx. MSDN page has a detailed C sample code.

Linux: check the "/proc/meminfo" file (discussion)

OSX: see this SO thread Determine physical mem size programmatically on OSX

The question is not clear, however. There is physical memory, there is virtual memory, there is an OS ability to swap some unused pages to disk/other storage.

If you need to write some kind of a system monitor, then my answer would do.

If you need to be sure that none of your malloc()/new[] calls fail, then just catch appropriate exceptions or handle NULL results. The other option is to build your own allocator which gets a large memory block at the beginning and allocates smaller blocks there.

EDIT: answer to comment

The calls to WinAPI's MapViewOfFile and CreateFileMapping provide error codes to exclude fatal situations. Since files are mapped to the virtual address space shared with your process' data, you may check if there are sufficient number of pages available. I.e., if you're on a 32-bit system, you won't be able to map the whole 8Gb file to the memory at once (but you can map its smaller parts), but on a 64-bit system the mapping possibilities are sufficient for any current needs.

这篇关于C ++检查可用ram?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆