【发布时间】:2015-01-21 23:57:27
【问题描述】:
我分配了 512mb 的内存,然后我每 4096 个字节修改一次(这应该会导致每次修改都会出现轻微的页面错误,这就是我实际得到的)。但随后我重复相同的循环,它再次导致每个请求出现轻微的页面错误。我的问题是,为什么?
输出如下所示:
但是,如果我从程序中删除调用 ps,则执行第二个循环所需的时间要低得多,例如 0.04 秒。为什么?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <unistd.h>
using namespace std;
const int sz = 512 * 1024 * 1024;
int main()
{
char * data = (char *)malloc(sz);
if (data == 0) cout << "alloc fail";
stringstream cmd;
cmd << "ps -o min_flt,maj_flt " << getpid();
system(cmd.str().c_str());
cout << "start\n";
clock_t start = clock();
for (int i=0; i<sz; i += 4096)
data[i] = 1;
clock_t end = clock();
double time1 = double(end-start) / CLOCKS_PER_SEC;
system(cmd.str().c_str());
start = clock();
for (int i = 0; i < sz; i += 4096)
data[i] = 1;
end = clock();
double time2 = double(end-start) / CLOCKS_PER_SEC;
system(cmd.str().c_str());
cout << time1 << " " << time2 << endl;
}
【问题讨论】:
-
你为什么用
malloc()而不是new()? -
for (int i=0; i<sz; i += 4096) data[i] = 1;你应该确保你的索引在范围内 -
大概是因为设置一个 shell 然后让它调用
ps使用了足够的内存,系统会分页出一些新创建的页面。你有多少内存? -
@frp “不会改变结果。” 我不怀疑。但是对于 c++ 代码,您应该使用
new(),或者更好的是std::vector<char>。 -
@frp:顺便说一下,在linux上你可以直接从
/proc/self/stat读取进程统计信息;minflt和majflt是(当前)返回行中的第 10 个和第 12 个元素(这是一系列以空格分隔的字段,旨在与scanf一起阅读)。有关字段列表,请参阅man 5 proc。