File size computation benchmark: C two times slower than C++? -
consider following code 3 different versions of file size computation.
#include <iostream> #include <cstdio> #include <string> #include <fstream> inline long long int filesize1(const std::string& filename) { std::ifstream filestream(filename.c_str(), std::ios::binary); std::streampos first = 0; std::streampos last = 0; long long int size = -1; if (filestream.is_open()) { filestream.seekg(0, std::ios::beg); first = filestream.tellg(); filestream.seekg(0, std::ios::end); last = filestream.tellg(); if ((first != -1) && (last != -1) && (last-first >= 0)) { size = last-first; } filestream.close(); } return size; } inline long long int filesize2(const std::string& filename) { std::ifstream filestream(filename.c_str(), std::ios::binary); return (filestream) ? (static_cast<long long int>(filestream.seekg(0, std::ios::end).tellg()-filestream.seekg(0, std::ios::beg).tellg())) : (-1ll); } inline long long int filesize3(const std::string& filename) { std::file* file = std::fopen(filename.c_str(), "rb"); long long int size = -1; if (file) { std::fseek(file, 0, seek_end); size = std::ftell(file); std::fclose(file); } return size; } int main(int argc, char* argv[]) { unsigned int n = 0; switch (std::atoi(argv[1])) { case 1: (int = 0; < std::atoi(argv[3]); ++i) n += filesize1(argv[2]); break; case 2: (int = 0; < std::atoi(argv[3]); ++i) n += filesize2(argv[2]); break; case 3: (int = 0; < std::atoi(argv[3]); ++i) n += filesize3(argv[2]); break; } std::cout<<n<<std::endl; return 0; }
first question : have guarantee in cases have same result 3 different versions ?
second question : why version 3 in c approximately 2 times slower first 2 versions ?
Comments
Post a Comment