如果你以root身份运行它,为什么这个C ++程序需要很长时间才能完成?

时间:2022-06-19 03:49:44

I want to clear L1, L2 and L3 cache 50 times by executing the following code. However it becomes very slow if I run it by typing sudo ./a.out. On the other hand, if I just write ./a.out it will finish executing almost instantly. I do not understand the reason for this since I am not getting any errors in the terminal.

我想通过执行以下代码清除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;
};

1 个解决方案

#1


14  

You don't have enough permissions to write to this file as a regular user:

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

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

Only version run as a privileged user works, hence it takes longer. The reason you're not getting any errors is that you're not checking any errors.

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

Here's the most simple check:

这是最简单的检查:

#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;
};

Output:

% ./a.out    
could not open file

#1


14  

You don't have enough permissions to write to this file as a regular user:

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

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

Only version run as a privileged user works, hence it takes longer. The reason you're not getting any errors is that you're not checking any errors.

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

Here's the most simple check:

这是最简单的检查:

#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;
};

Output:

% ./a.out    
could not open file