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

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

#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;
};
+4
source share
1 answer

You do not have sufficient 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 the privileged user version works, so it takes more time. The reason you are not getting any errors is because you are not checking for any errors.

:

#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
+14

All Articles