2015-02-11 79 views
4

我想通过执行以下代码清除L1,L2和L3缓存50次。但是,如果通过输入sudo ./a.out来运行它,它会变得非常缓慢。另一方面,如果我只写./a.out它将几乎立即完成执行。我不明白这个原因,因为我没有在终端发生任何错误。为什么这个C++程序需要很长时间才能完成,如果你以root身份运行它?

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

定义 “非常缓慢”。也许sudo版本实际上设置了它,而另一个则忽略了你的请求。首先这似乎是一件奇怪的事情。你的目标是什么?如果以root身份运行它,则可以使用 – tadman 2015-02-11 14:57:25

+0

〜10秒。 – jsguy 2015-02-11 14:58:04

+0

'sudo'其他什么都需要至少十秒钟?这个操作需要多长时间才能通过shell完成?您通常可以使用'time'命令进行检查。 – tadman 2015-02-11 14:58:33

回答

14

您没有足够的权限来写入该文件作为一个普通用户:

-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 
相关问题