如果你以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
相关文章:
- 使用简单类型列表实现的指数编译时间.为什么
- 使用Boost Interprocess创建托管共享内存需要很长时间
- SFML RenderWindow打开窗口需要很长时间
- Kafka C++客户端需要很长时间才能收到消息
- 给定使用 C++ 或 C,我如何测量在 linux 下进行线程切换需要多长时间?可能吗?
- asio::read() 需要很长时间,使用 asio::write 没有问题
- 将线程锁定很长时间
- 正在等待在非阻塞文件描述符上长时间运行ioctl
- C++,自使用boost和std::chrono的纪元以来的时间?为什么 Boost 版本慢 10 倍?
- 即使长时间等待,C++线程也不会加入
- 连接() 在连接被拒绝时长时间挂起
- 为什么这段代码需要这么长时间才能用 g++ 编译?
- 为什么与Java和Python相比,使用Cmake运行C++程序每次都需要这么长时间?
- 为什么编译超过100000行std::vector::push_back需要很长时间
- 如果你以root用户身份运行这个C++程序,为什么它要花这么长时间才能完成
- 为什么具有多个嵌套循环的代码可以在 GCC 上立即完成,但在 VS 上需要很长时间
- 为什么我的简单cpp-netlib程序需要这么长时间才能编译
- 为什么for循环要花这么长时间
- 为什么终端需要这么长时间才能启动?c++
- 为什么与 C 和 C++ 相比,C# 代码需要很长时间才能执行