Fastest way to check if a file exist using standard C++/C++11,14,17/C?(使用标准 C++/C++11,14,17/C 检查文件是否存在的最快方法?)
问题描述
我想找到检查标准 C++11、14、17 或 C 中是否存在文件的最快方法.我有数千个文件,在对它们执行某些操作之前,我需要检查是否所有文件都存在存在.我可以在下面的函数中写什么来代替 /* 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 */
}
推荐答案
好吧,我拼凑了一个测试程序,该程序运行这些方法中的每一种 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);
}
运行 100,000 次调用的总时间平均超过 5 次运行的结果,
Results for total time to run the 100,000 calls averaged over 5 runs,
| 方法 | 时间 |
|---|---|
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() 函数在我的系统(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,14,17/C 检查文件是否存在的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用标准 C++/C++11,14,17/C 检查文件是否存在的最快
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
