Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么这个C++;如果以根用户身份运行,程序需要很长时间才能完成?_C++_Caching - Fatal编程技术网

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

C++ 为什么这个C++;如果以根用户身份运行,程序需要很长时间才能完成?,c++,caching,C++,Caching,我想通过执行以下代码来清除L1、L2和L3缓存50次。但是,如果我通过键入sudo./a.out来运行它,它会变得非常慢。另一方面,如果我只写/a.out,它几乎会立即完成执行。我不明白这是什么原因,因为我在终端中没有收到任何错误 #include <iostream> #include <cstdlib> #include <vector> #include <fstream> #include <unistd.h> using n

我想通过执行以下代码来清除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;
};
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
void clear_cache(){
sync();
std::ofs流(“/proc/sys/vm/drop_缓存”);

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

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

定义“非常慢”。也许sudo版本确实设置了它,而另一个版本只是忽略了您的请求。这首先看起来很奇怪。您的目标是什么?如果以根用户身份运行,则大约需要10秒。
sudo
其他任何操作是否至少需要10秒?此操作需要多长时间才能通过shell完成?您通常可以在g使用
time
命令。不,仅此程序清除内核缓存,而不是CPU缓存。我不确定是否有办法从userland执行此操作,但您肯定不想执行此操作。(是如何从内核执行此操作)。
% ./a.out    
could not open file