使用标准C ++ / C ++ 11 / C检查文件是否存在最快的方法? [英] Fastest way to check if a file exist using standard C++/C++11/C?
问题描述
我想找到最快的方式来检查文件是否存在于标准C ++ 11,C ++或C中。我有数千个文件,在对其进行处理之前,我需要检查它们是否存在。在以下功能中可以写入什么,而不是 / * SOMETHING * /
?
I would like to find the fastest way to check if a file exist in standard C++11, C++, or C. I have thousands of files and before doing something on them I need to check if all of them exist. What can I write instead of /* SOMETHING */
in the following function?
inline bool exist(const std::string& name)
{
/* SOMETHING */
}
推荐答案
程序运行这些方法100,000次,一半存在文件,一半在没有的文件上。
Well I threw together a test program that ran each of these methods 100,000 times, half on files that existed and half on files that didn't.
#include <sys/stat.h>
#include <unistd.h>
#include <string>
inline bool exists_test0 (const std::string& name) {
ifstream f(name.c_str());
return f.good();
}
inline bool exists_test1 (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
inline bool exists_test2 (const std::string& name) {
return ( access( name.c_str(), F_OK ) != -1 );
}
inline bool exists_test3 (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
在5次运行中平均运行100,000次通话的总时间的结果
Results for total time to run the 100,000 calls averaged over 5 runs,
Method exists_test0 (ifstream): **0.485s**
Method exists_test1 (FILE fopen): **0.302s**
Method exists_test2 (posix access()): **0.202s**
Method exists_test3 (posix stat()): **0.134s**
stat()函数在我的系统上提供了最好的性能(Linux,使用g ++编译),标准的fopen调用是您最好的选择,有些原因拒绝使用POSIX功能。
The stat() function provided the best performance on my system (Linux, compiled with g++), with a standard fopen call being your best bet if you for some reason refuse to use POSIX functions.
这篇关于使用标准C ++ / C ++ 11 / C检查文件是否存在最快的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!