Speed up cimg::fsize#484
Conversation
c6e5e82 to
2131624
Compare
|
Conflicts are resolved. |
2131624 to
4c10edc
Compare
|
The optimization path for Windows has also been added. |
|
I've included/rewritten your patch, with a few changes for better portability : //! Get file size.
/**
\param file Specified file to get size from.
\return File size or '-1' if file does not exist.
**/
inline cimg_int64 fsize(std::FILE *const file) {
if (!file) return (cimg_int64)-1;
#if cimg_OS==1 // Optimized for POSIX Environements (Linux, macOS, BSD, etc.)
const int fd = fileno(file);
struct stat st;
if (fd>=0 && !fstat(fd,&st)) return (cimg_int64)st.st_size;
#elif cimg_OS==2 // Optimized for Windows Environements (MSVC, MinGW)
const int fd = _fileno(file);
struct _stati64 st;
if (fd>=0 && !_fstati64(fd,&st)) return (cimg_int64)st.st_size;
#endif
// Fallback, used for non-POSIX systems or if fstat failed (pipes or sockets).
const cimg_long pos = cimg::ftell(file);
cimg::fseek(file, 0, SEEK_END);
const cimg_int64 siz = (cimg_int64)cimg::ftell(file);
cimg::fseek(file, pos, SEEK_SET);
return siz;
}
//! Get file size from filename.
/**
\param filename Specified filename to get size from.
\return File size or '-1' if file does not exist.
**/
inline cimg_int64 fsize(const char *const filename) {
if (!filename || !*filename) return (cimg_int64)-1;
#if cimg_OS==1 // Optimized for POSIX Environements (Linux, macOS, BSD, etc.)
struct stat st;
if (!stat(filename,&st)) return (cimg_int64)st.st_size;
#elif cimg_OS==2 // Optimized for Windows Environements (MSVC, MinGW)
// Convert UTF-8 path to wchar_t.
int len = MultiByteToWideChar(CP_UTF8,0,filename,-1,0,0);
if (len>0) {
CImg<wchar_t> wfilename((unsigned int)len);
if (MultiByteToWideChar(CP_UTF8,0,filename,-1,wfilename,len)) {
struct _stati64 st;
if (!_wstati64(wfilename,&st)) return (cimg_int64)st.st_size;
}
}
#endif
// Fallback.
std::FILE *const file = cimg::std_fopen(filename, "rb");
if (!file) return (cimg_int64)-1;
const cimg_int64 siz = cimg::fsize(file);
cimg::fclose(file);
return siz;
}What do you think ? |
4c10edc to
72b009f
Compare
@dtschump That's great! Additionally, |
|
OK, I've tested on Windows, and it does not work. I had to do other modifications to make it work. |
72b009f to
ee49a5e
Compare
|
I resolved the conflict. _filelengthi64 also no need to check fd so I removed the "if (fd>=0)" |
ee49a5e to
ee6abc9
Compare
|
@dtschump I fixed Windows code. Please take a look. |
|
P.S. I don't really recommend using the POSIX-compatible functions provided by crt; they're slower than the native API and behave differently from POSIX. |
In a POSIX environment, there is a faster way to retrieve a file's size that does not modify the file offset.
This can roughly improve
fsizeperformance by 3x–10xBenchmark code:
Results: