如果您 运行 作为 root,为什么这个 C++ 程序需要这么长时间才能完成?

Why does this C++ program take so long to finish if you run it as a root?

我想通过执行以下代码清除 L1、L2 和 L3 缓存 50 次。但是,如果我通过键入 sudo ./a.out 运行 它会变得非常慢。另一方面,如果我只写 ./a.out 它几乎会立即完成执行。我不明白这是为什么,因为我在终端中没有收到任何错误。

#include <iostream>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <unistd.h>

using namespace std;

void clear_cache(){
    sync();
    std::ofstream ofs("/proc/sys/vm/drop_caches");
    ofs << "3" << std::endl;
    sync();
}


int main() {

    for(int i = 0; i < 50; i++)
        clear_cache();

    return 0;
};

您没有足够的权限以普通用户身份写入此文件:

-rw-r--r-- 1 root root 0 Feb 11 15:56 /proc/sys/vm/drop_caches

只有作为特权用户的版本 运行 才有效,因此需要更长的时间。您没有收到任何错误的原因是您没有检查任何错误。

这是最简单的检查:

#include <iostream>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <unistd.h>

using namespace std;

void clear_cache(){
    sync();
    std::ofstream ofs("/proc/sys/vm/drop_caches");

    if (!ofs)
    {
        std::cout << "could not open file" << std::endl;
        exit(EXIT_FAILURE);
    }

    ofs << "3" << std::endl;
    sync();
}


int main() {

    for(int i = 0; i < 50; i++)
        clear_cache();

    return 0;
};

输出:

% ./a.out    
could not open file