網站首頁 編程語言 正文
1. 敘述?
對于讀取本地文件,很多時候需要預先知道本地文件的大小在進行讀取。網上給出的方案是移動文件指針,計算文件頭和文件尾的偏移,計算出文件的大小。但是我總覺得這樣做可能會與讀取文件一樣消耗性能,為了解決這個問題,我寫了如下例子驗證了一下。
#include <iostream> #include <fstream> #include<Windows.h> using namespace std; class CTimer { public: CTimer(void); ~CTimer(void); int time_in(); double time_out(); private: LARGE_INTEGER litmp; LONGLONG qt1, qt2; double dft, dff, dfm; }; CTimer::CTimer(void) { } CTimer::~CTimer(void) { } int CTimer::time_in() { QueryPerformanceFrequency(&litmp);//獲得時鐘頻率 dff = (double)litmp.QuadPart; QueryPerformanceCounter(&litmp);//獲得初始值 qt1 = litmp.QuadPart; return 1; } double CTimer::time_out() { QueryPerformanceCounter(&litmp);//獲得終止值 qt2 = litmp.QuadPart; dfm = (double)(qt2 - qt1); dft = dfm / dff;//獲得對應的時間值 return dft; } int main() { string file_name = "D:/Work/test.zip"; CTimer timer; ifstream ifs(file_name, std::ios::binary | std::ios::in); if (!ifs.is_open()) { return 0; } timer.time_in(); ifs.seekg(0, std::ios::end); int len = ifs.tellg(); ifs.seekg(0, std::ios::beg); cout << "獲取文件長度耗時:" << timer.time_out() << "秒" << endl; timer.time_in(); char *buff = new char[len]; ifs.read(buff, len); delete[]buff; timer.time_out(); cout << "讀取文件耗時:" << timer.time_out() << "秒" << endl; return 1; }
如上所示,我寫了一個計時器,分別統計偏移文件指針計算文件長度與讀取整個文件的耗時,運行結果如下:
2. 結論
可以看到,偏移文件指針帶來的時間消耗非常小,幾乎可以忽略不記。通過這個方法,不僅可以很快計算文件長度,還可以根據需要讀取文件的特定位置,從而達到節省性能的目的。
原文鏈接:https://www.cnblogs.com/charlee44/p/15487967.html
相關推薦
- 2023-03-22 C++類中const修飾的成員函數及日期類小練習_C 語言
- 2023-03-26 數據結構TypeScript之棧和隊列詳解_其它
- 2022-02-27 Required String paramter ‘username‘ is not present
- 2022-09-29 Python?pkg_resources模塊動態加載插件實例分析_python
- 2022-12-19 批處理bat腳本獲取打包發布問題記錄_DOS/BAT
- 2022-04-16 Android中RecyclerView實現簡單購物車功能_Android
- 2022-12-07 利用C語言模擬實現qsort,strcpy,strcat,strcmp函數_C 語言
- 2022-11-13 C語言在輸入輸出時遇到的常見問題總結_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支