問題描述
我想找到檢查標(biāo)準(zhǔn) C++11、14、17 或 C 中是否存在文件的最快方法.我有數(shù)千個(gè)文件,在對(duì)它們執(zhí)行某些操作之前,我需要檢查是否所有文件都存在存在.我可以在下面的函數(shù)中寫什么來代替 /* SOMETHING */
?
I would like to find the fastest way to check if a file exist in standard C++11,14,17, 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 */
}
推薦答案
好吧,我拼湊了一個(gè)測(cè)試程序,該程序運(yùn)行這些方法中的每一種 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>
#include <fstream>
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);
}
運(yùn)行 100,000 次調(diào)用的總時(shí)間平均超過 5 次運(yùn)行的結(jié)果,
Results for total time to run the 100,000 calls averaged over 5 runs,
方法 | 時(shí)間 |
---|---|
exists_test0 (ifstream) | 0.485s |
exists_test1 (FILE fopen) | 0.302s |
exists_test2 (posix access()) | 0.202s |
exists_test3 (posix stat()) | 0.134s |
Method | Time |
---|---|
exists_test0 (ifstream) |
0.485s |
exists_test1 (FILE fopen) |
0.302s |
exists_test2 (posix access()) |
0.202s |
exists_test3 (posix stat()) |
0.134s |
stat()
函數(shù)在我的系統(tǒng)(Linux,使用 g++
編譯)上提供了最佳性能,標(biāo)準(zhǔn)的 fopen
調(diào)用是如果您出于某種原因拒絕使用 POSIX 函數(shù),那么您最好的選擇.
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.
這篇關(guān)于使用標(biāo)準(zhǔn) C++/C++11,14,17/C 檢查文件是否存在的最快方法?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!