目前,有很多清理内存的工具,如Wise Memory Optimizer、 MemoryZipperPlus、SweepRAM等,360安全卫士、腾讯电脑管家、鲁大师等等系统工具也带有清理内存的功能。

这些工具主要使用Windows提供的API:EmptyWorkingSet 或SetProcessWorkingSetSize 进行内存清理。

EmptyWorkingSet 强制将进程工作集中的内存尽可能多地移动到页面文件中 (Removes as many pages as possible from the working set of the specified process.),函数原型为:

BOOL WINAPI EmptyWorkingSet( _In_ HANDLE hProcess );

SetProcessWorkingSetSize可以设置进程工作集中内存的最大最小值(Sets the minimum and maximum working set sizes for the specified process.),函数原型为:

BOOL WINAPI SetProcessWorkingSetSize( _In_ HANDLE hProcess, _In_ SIZE_T dwMinimumWorkingSetSize, _In_ SIZE_T dwMaximumWorkingSetSize );其中,如果后两个参数均为-1时,该函数效果与EmptyWorkingSet相同(The working set of the specified process can be emptied by specifying the value (SIZE_T)–1 for both the minimum and maximum working set sizes. This removes as many pages as possible from the working set. The EmptyWorkingSet function can also be used for this purpose.)。

使用上面介绍的API,我们就可以实现自己的内存清理工具:

第一步,提升程序进程权限,两个API函数均需要传入要清理的线程句柄,该句柄可以通过OpenProcess得到,而如果进程权限不够,将导致打开进程失败。

准确地说,不是提升权限,而是把令牌中禁用的权限启用。MSDN上指出,如果需要打开其他进程并获得所有权限,需要启用SeDebugPrivilege权限(To open a handle to another process and obtain full access rights, you must enable the SeDebugPrivilege privilege)。

提升权限时,需要用到的API有:OpenProcessToken、LookupPrivilegeValue、AdjustTokenPrivileges、CloseHandle,MSDN上有详细的用法讲解(Enabling and Disabling Privileges in C++),在这不一一介绍了,下面给出程序提权部分代码:

BOOL EnableDebugPrivilege { BOOL bRet = FALSE; HANDLE hToken; if (::OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, &hToken)) { LUID luid; if (::LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) { TOKEN_PRIVILEGES tp; tp.PrivilegeCount = 1UL; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (::AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL)) { bRet = TRUE; } } ::CloseHandle(hToken); } return bRet; }第二步就是遍历系统所有进程,调用上面两个函数传入的只是一个进程的句柄,也就是说每次调用只针对于一个进程的内存空间,所以我们还需要遍历整个系统的所有进程,然后获取每个进程的句柄,将该句柄当做参数传入上面两个函数。遍历系统所有进程有很多方法,这里使用ToolHelp API获取。其中用到3个API函数:CreateToolhelp32Snapshot、Process32First、Process32Next,MSDN上对其用法已经有详细的介绍(Taking a Snapshot and Viewing Processes),这里也不再一一介绍。

第三步自然就是在上面遍历过程中调用EmptyWorkingSet 或 SetProcessWorkingSetSize 来实现清理内存。下面给出实现代码,代码中使用的是SetProcessWorkingSetSize函数,懒得包含EmptyWorkingSet需要的Psapi.h头文件。

BOOL EmptyAllProcess { BOOL bRet = FALSE; HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap != INVALID_HANDLE_VALUE) { PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); if (::Process32First(hProcessSnap, &pe32)) { do { HANDLE hProcess = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); if (hProcess) { ::SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1); ::CloseHandle(hProcess); } } while (::Process32Next(hProcessSnap, &pe32)); bRet = TRUE; } ::CloseHandle(hProcessSnap); } return bRet; }

第四步,为了更加直观的显示优化后所腾出的内存空间,可以在清理前后获取系统内存使用状态。这里用到GlobalMemoryStatusEx函数来获取当前系统物理内存与虚拟内存。GlobalMemoryStatus函数也可以获取,但在内存超过4GB时得到的结果不正确(On computers with more than 4 GB of memory, the GlobalMemoryStatus function can return incorrect information, reporting a value of –1 to indicate an overflow. )。程序中参照MSDN上的例子打印出内存的使用状况。

程序为了简便,使用了控制台工程,运行后截图如下:

完整的程序及源代码下载链接:

看了上面介绍,相信大部分人会认为这是一个非常有效的方法,能够腾出大量内存,明显减小内存的占用率。殊不知,这种伎俩其实只是一种假象,所有的努力可能只会让事情变得更加糟糕!不信继续往下看。

为什么这么说呢,因为使用上面两个API并不能减小程序的内存,只不过是强制将正在运行的程序工作内存写入Windows的页面文件。这样看似内存使用量是下降了,其实只不过是把内存转到了慢速存储之中。当程序再次需要使用到这些内存时,由于内存已经移入页面文件,虚拟内存位置被标记为了"不存在",这时将会产生一个缺页中断,也就是平常说的页面错误,这时,操作系统又不得不重新将这些内存由硬盘移到内存之中。

比如你正在看一个视频,现在先暂停它,接着使用内存清理工具来“清理”内存。清理完后,你再回过头来继续播放刚才的视频或者执行其他程序,你会发现,程序略有卡顿(对于小内存机器尢为明显),在卡顿过后,系统的内存又有所上升,一段时间后,内存使用量也慢慢又涨上去了。如果你在刚清理后使用某个程序并在系统任务管理器里查看进程信息(需要在“选择列”对话框中选中“页面错误增量”),你会发现该程序的页面错误增量会明显地增加,这个时候系统就正在把内存重新搬回到工作集内存之中。

有一篇写得很好的文章,详细说明了这一问题,文章链接:点击打开链接,在此顺便也贴出这篇文章:

Why Memory Optimizers and RAM Boosters Are Worse ThanUseless

Many companies want to sell you “memoryoptimizers,” often as part of “PC optimization” programs. These programs areworse than useless — not only will they not speed up your computer, they’llslow it down.

Such programs take advantage ofinexperienced users, making false promises about boosting performance. Inreality, your computer knows how to manage RAM on its own. It will use RAM toincrease your computer’s performance — there’s no point in having RAM sitempty.

Is Your Computer’s RAM Filling Up? That’s Good!

Memory optimizers are based on amisunderstanding. You may look at your computer’s RAM and see it filling up —for example, you may have 4 GB of RAM and see that 3 GB is full with only 1 GBto spare. That can be surprising to some people — look how bloated modernversions of Windows are! How are you ever going to run additional programs withso little memory available?

In reality, modern operating systems arepretty good at managing memory on their own. That 3 GB of used RAM doesn’tnecessarily indicate waste. Instead, your computer uses your RAM to cache datafor faster access. Whether it’s copies of web pages you had open in yourbrowser, applications you previously opened, or any other type of data youmight need again soon, your computer hangs onto it in its RAM. When you needthe data again, your computer doesn’t have to hit your hard drive — it can justload the files from RAM.

Crucially, there’s no point inhaving RAM empty. Even if your RAM is completely full and your computer needsmore of it to run an application, your computer can instantly discard thecached data from your RAM and use that space for the application. There’s nopoint in having RAM sit empty — if it’s empty, it’s being wasted. If it’s full,there’s a good chance it can help speed up program loading times and anythingelse that would use your computer’s hard drive.

Notice that very little RAM is actually“free” in the screenshot below. The RAM is being used as a cache, but it’sstill marked as available for any program that needs to use it.

In the past, full RAM did indicate aproblem. If you were running Windows Vista on a computer with half a gig ofRAM, you could feel the computer constantly slowing down — it had to constantlyread and write to the hard drive, using the hard drive’s page file as aninefficient replacement for RAM. However, modern computers generally haveenough RAM for most users. Even low-end computers generally ship with 4GB of RAM, which should be more than enough unless you’re doing intensive gaming,running multiple virtual machines, or editing videos.

Even if RAM was a problem for you,there’s no reason to use a memory optimizer. Memory optimizers are snake oilthat are useless at best and harmful at worst.

How Memory Optimizers Work

When you use a memory optimizer, you’llsee your computer’s RAM usage go down. This may seem like an easy win — you’vedecreased RAM usage just be pressing a button, after all. But it’s not thatsimple.

Memory optimizers actually work in oneof two ways:

· They call the EmptyWorkingSet Windows API function,forcing running applications to write their working memory to the Windows pagefile.

· They quickly allocate a large amount of memory tothemselves, forcing Windows to discard cached data and write application datato the page file. They then deallocate the memory, leaving it empty.

Both of these tricks will indeed free upRAM, making it empty. However, all this does is slow things down — now theapplications you use will have to get the data they need from the page file,reading from the hard drive and taking longer to work. Any memory being usedfor cache may be discarded, so Windows will have to get the data it needs fromthe hard drive.

In other words, these programs free upfast memory by forcing data you need onto slower memory, where it will have tobe moved back to fast memory again. This makes no sense! All it accomplishes isselling you another system optimization program you don’t need.

If Windows needs RAM, it will push datato the page file or discard cached data, anyway. This all happens automaticallywhen it needs to — there’s no point in slowing things down by forcing it to happenbefore it's necessary.

Like PC cleaning apps, memoryoptimizers are a scam. They appear to be doing something positive to people whodon’t understand how memory management works, yubut they’re actually doingsomething harmful.

How to Actually “Optimize” Your Memory

If you do want to have more availableRAM, skip the memory optimizer. Instead, try to get rid of running applicationsyou don’t need — purge unnecessary programs from your system tray, disableuseless startup programs, and so on.

If you do need more RAM for what you do,try buying some more RAM. RAM is pretty cheap and it’s not too hard to installit yourself using one of the RAM installing guides available online.Just ensure you buy the correct type of RAM for your computer.

文中详细分析了这一现象的本质。对于现在的操作系统,并不是你内存空闲得越多,程序运行得就越快。就算内存真快耗尽,操作系统也会自动丢弃掉一部分缓存数据,同时将不频繁访问的页面从工作集中移出,暂时保存在内存中的“转换列表”中,或者进一步换出到页面文件中,完全没有理由也没有必要我们自己在不必要的时候做这些事。

所以,上面实现的程序只是一个简单地展示,以便大家明白清理内存的实际原理,不建议(甚至可以说不应该)用于解决内存不足的问题。

现在,基本各种内存清理工具使用的都是上面提到的方式,有的还允许设置自动清理,程序每隔一定时间自动进行清理...... 当你明白了这些工具的实现原理后,你会发现,这类工具仅仅是一个骗局而已,它们只不过安慰一下那些不懂内存管理的人,不但没什么贡献,反而会使你系统变得更慢。

除了使用这种方式,有些清理工具还进行暴力清理。这类工具自身大量申请内存,快速填满你的内存,这时你的系统会被迫丢弃大量缓存文件,同时调用转换操作,将其他进程的内存空间转换到虚拟内存。之后,这类工具再突然释放所申请的大量空间,让你觉得腾出了很大的空间。使用这种暴力清理可能腾出比使用EmptyWorkingSet或SetProcessWorkingSetSize更多的内存空间,但在所谓的“清理”过程中的开销也更大,最终同样也只是让事情变得更加糟糕。

也有部分清理内存工具,还会结束掉一些闲置的服务与一些进程的残留项以进一步减小内存使用量(如360安全卫士)。这种方式确实有一定的效果,能真正地腾出一定的空间。但由于可以结束的进程是有限的,而且这些进程所占内存往往不会太大,通常也不能够腾出多少内存空间,优化效果并不会明显。

综上,我个人认为,无论清理内存或者内存优化之类的工具没什么实用价值与实际意义。对于内存小的机器,它们只会更加拖慢你的系统;对于大内存的机器,就算它们有用,你也没有理由去用。所以,要解决内存不够的问题,最有效的方式就是——插内存条,插内存条,插内存条!

Windows内存清理工具实现——从现象到本质相关推荐

  1. windows内存清理工具

    功能: 1.每30分钟定时清理 2.后台清理 3.显示系统内存以及进程数信息 截图: 代码地址:https://github.com/zengge2/RAMCleaner 若程序有Bug请在评论区反馈 ...

  2. Windows内存清理----其实是没必要的

    Windows内存清理----其实是没必要的 目前,有很多清理内存的工具,如Wise Memory Optimizer. MemoryZipperPlus.SweepRAM等,360安全卫士.腾讯电脑 ...

  3. 国外android内存清理工具,小内存手机有救了,这款清理神器,瞬间多出几个G的内存...

    原标题:小内存手机有救了,这款清理神器,瞬间多出几个G的内存 今日分享:手机内存清理工具 适用系统:安卓 随着手机的内存越来越大,大家对于垃圾文件清理越来越不感冒,但这样好吗?这样不好,不仅让手机内存 ...

  4. 服务器系统盘清理工具,服务器内存清理工具

    服务器内存清理工具 内容精选 换一换 本章节指导用户通过Windows操作系统自带的磁盘清理工具来清理空间不足的磁盘.本文以操作系统为"Windows Server 2016 Standar ...

  5. VC.NET扩展Windows磁盘清理工具的功能

    介绍了Windows磁盘清理工具二次开发的扩展接口,对其COM接口加以分解,并运用ATL库具体实现了清理"*.tmp"临时文件的功能. 关键词 磁盘清理工具.ATL库.COM接口. ...

  6. 【Python】Windows微信清理工具

    本工具采用Python编写,先读取"%userprofile%\AppData\Roaming\Tencent\WeChat\All Users\config\3ebffe94.ini&qu ...

  7. 一个小巧的WINDOWS垃圾清理工具

    一个小巧的WINDOWS垃圾清理工具 附件:http://down.51cto.com/data/2348167 本文转自 saturn 51CTO博客,原文链接:http://blog.51cto. ...

  8. C#实现的系统内存清理工具

    金山内存整理工具.360内存清理工具非常好用,可以将系统内存最小化,提升系统运行速度.其实这些事情C#也可以做到,原理就是对系统进程中的进程内存进行逐个优化. 网上大多推荐使用系统的SetProces ...

  9. SmartMemoryCleaner for Mac(内存清理工具)

    本次小编为您带来SmartMemoryCleaner for Mac,这是Mac平台上能够为您清理系统中多余的内容,释放您的内存的一款内存清理工具.SmartMemoryCleaner mac兼容多个 ...

最新文章

  1. C++:随笔8---命名空间
  2. 如何在XML中注释掉一个标签块?
  3. 飞机大作战游戏 1----(运用H5和Js制作)
  4. Ogre共享骨骼与两种骨骼驱动方法
  5. Linux高级文本处理之sed(三)
  6. 2021.9.23模拟
  7. oracle asm 分布式存储,分布式数据中心数据库和存储部署解决方案
  8. 傅里叶变换对噪声进行频谱分析
  9. POJ2104 K-th number 函数式线段树
  10. c++全局变量怎么定义_C errno全局变量是否是线程安全的
  11. django中settings中文解释
  12. matlab软件编程求解方程实验报告,数学实验“线性方程组高斯消去法”实验报告内含matlab程序.doc...
  13. 实践小笔记(1) --- DBSCAN
  14. 新浪微博广告形式全攻略
  15. 达梦数据库的替代(instead of )触发器使用一例
  16. cshop模板smarty foreach详解
  17. Qt数据库应用23-个人信息报表
  18. 传输层协议——UDP和TCP
  19. 前后端分离状态保持问题之JWT
  20. C语言 —— 一分钟让你理解自增和自减

热门文章

  1. Ubuntu出现device not managed 如何解决?
  2. Android逆向:去除RE管理器4.41及车来了广告
  3. 大型企业CA认证系统部署应用案例解析
  4. MATLAB学习——低通滤波(频域滤波(一))
  5. 单个正态总体参数的区间估计、两个正态总体参数的区间估计 Matlab实现
  6. 【已解决】Spring容器中找不到ServletWebServerFactory类出现的异常
  7. sql 2000及SP4 安装
  8. vivox6android版本5.1,vivo X6的手机系统是什么?vivo X6能升级安卓5.0吗?
  9. 【实战】PyTorch 在 CIFAR-10 数据集上的训练及测试过程
  10. 如何查看笔记本电脑固态硬盘接口与接口协议