我们设置了两个相同的HP Z840工作站,其规格如下
并在每个上安装了Windows 7 SP1(x64)和Windows 10 Creators Update(x64).
然后我们运行了一个小内存基准测试(下面的代码,使用VS2015 Update 3,64位架构构建),它可以同时从多个线程执行内存分配 - 无填充.
#include <Windows.h>
#include <vector>
#include <ppl.h>
unsigned __int64 ZQueryPerformanceCounter()
{
unsigned __int64 c;
::QueryPerformanceCounter((LARGE_INTEGER *)&c);
return c;
}
unsigned __int64 ZQueryPerformanceFrequency()
{
unsigned __int64 c;
::QueryPerformanceFrequency((LARGE_INTEGER *)&c);
return c;
}
class CZPerfCounter {
public:
CZPerfCounter() : m_st(ZQueryPerformanceCounter()) {};
void reset() { m_st = ZQueryPerformanceCounter(); };
unsigned __int64 elapsedCount() { return ZQueryPerformanceCounter() - m_st; }; …Run Code Online (Sandbox Code Playgroud) windows memory-management windows-7 windows-10 windows-server-2016
所以我有这个程序分配256 MB的内存,并在用户按下ENTER后释放内存并终止.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *p, s[2];
p = malloc(256 * 1024 * 1024);
if ( p == NULL)
exit(1);
printf("Allocated");
fgets(s, 2, stdin);
free(p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我多次运行这个程序并对每个程序进行后台处理,直到没有足够的内存可以分配.但是,这从未发生过.我运行了一个linux top命令,甚至在多次运行这个程序之后,空闲内存永远不会下降到256 MB.
但是,另一方面,如果我使用calloc而不是malloc那时有一个巨大的差异:
p = calloc(256 * 1024 * 1024, 1);
现在,如果我运行该程序并对其进行后台处理,并重复,每次运行它时,可用内存将减少256 MB.为什么是这样?为什么不会malloc导致可用的可用内存发生变化,但是calloc呢?