Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

caching

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.

#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;
};
like image 226
jsguy Avatar asked Dec 08 '22 04:12

jsguy


1 Answers

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
like image 76
Nemanja Boric Avatar answered Dec 28 '22 22:12

Nemanja Boric