메모리 맵 파일강의 숙제 검사
안녕하세요 선생님. 메모리 맵 파일강의 에서 내주신 숙제를 풀어 봤는데, 혹시 검사 부탁드려도 될까요?
아래의 코드가 제가 작성한 코드인데 혹시 잘못된 부분이나 고치면 좋겠다 하는 부분을 알려주시면 대단히 감사하겠습니다. 그리고 따로 질문 사항이 아래와 같이 있습니다.
메모리 맵 방식이 WriteFile() 방식보다 쓰기 속도가 더 빠를까요?
chunkSize를 높여서 한번에 wirte하면 더 빠르다 강의에서 하셨는데, 어떠한 기준으로 메모리 효율이나 쓰기속도를 고려한 chunkSize의 최적의 사이즈를 구할수 있을까요?
항상 좋은 강의 만들어 주셔서 감사합니다!
#include <iostream>
#include <windows.h>
// Custom deleter for HANDLE
struct HandleDeleter {
void operator()(HANDLE handle) {
if (handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
}
}
};
typedef std::unique_ptr<std::remove_pointer<HANDLE>::type, HandleDeleter> UniqueHandle;
int main() {
_wsetlocale(LC_ALL, L"korean");
const wchar_t* sourceFilePath = L"C:\\TEST\\Sleep Away.zip";
const wchar_t* targetFilePath = L"C:\\TEST\\Sleep Away - copy.zip";
// Open source file
UniqueHandle hFileSource{ CreateFile(sourceFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL) };
if (hFileSource.get() == INVALID_HANDLE_VALUE) {
wprintf(L"Failed to open source file [ERROR CODE: %d]\n", GetLastError());
return 0;
}
// Open target file
UniqueHandle hFileTarget{ CreateFile(targetFilePath, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL) };
if (hFileTarget.get() == INVALID_HANDLE_VALUE) {
wprintf(L"Failed to open target file [ERROR CODE: %d]\n", GetLastError());
return 0;
}
// Set the size of the target file to match the source file
LARGE_INTEGER fileSize;
GetFileSizeEx(hFileSource.get(), &fileSize);
if (!SetFilePointerEx(hFileTarget.get(), fileSize, nullptr, FILE_BEGIN) || !SetEndOfFile(hFileTarget.get())) {
wprintf(L"Failed to set size of target file [ERROR CODE: %d]\n", GetLastError());
return 0;
}
// Create file mappings
UniqueHandle hMapSource{ CreateFileMapping(hFileSource.get(), NULL, PAGE_READONLY, 0, 0, NULL) };
UniqueHandle hMapTarget{ CreateFileMapping(hFileTarget.get(), NULL, PAGE_READWRITE, 0, 0, NULL) };
if (hMapSource.get() == nullptr || hMapTarget.get() == nullptr) {
wprintf(L"Failed to create file mappings [ERROR CODE: %d]\n", GetLastError());
return 0;
}
// Constants for the operation
const DWORD chunkSize = 65536; // 64 KB
DWORD bytesCopied = 0;
for (LONGLONG offset = 0; offset < fileSize.QuadPart; offset += chunkSize) {
DWORD size = static_cast<DWORD>(min(static_cast<LONGLONG>(chunkSize), fileSize.QuadPart - offset));
// Map a chunk from the source file
auto pSrc = static_cast<char*>(MapViewOfFile(hMapSource.get(), FILE_MAP_READ, 0, offset, size));
if (pSrc == nullptr) {
wprintf(L"Failed to map view of source file [ERROR CODE: %d]\n", GetLastError());
break;
}
// Map a chunk to the target file
auto pDst = static_cast<char*>(MapViewOfFile(hMapTarget.get(), FILE_MAP_WRITE, 0, offset, size));
if (pDst == nullptr) {
wprintf(L"Failed to map view of target file [ERROR CODE: %d]\n", GetLastError());
UnmapViewOfFile(pSrc);
break;
}
// Copy the chunk
memcpy(pDst, pSrc, size);
bytesCopied += size;
wprintf(L"%I64d%%\n", offset * 100 / fileSize.QuadPart);
// Unmap the chunks
UnmapViewOfFile(pSrc);
UnmapViewOfFile(pDst);
}
wprintf(L"Copy complete! The original file size is %lld bytes and %d bytes copied.\n", fileSize.QuadPart, bytesCopied);
return 0;
}
답변 1
0
for loop를 사용할 이유가 없습니다. 원본 파일에 대한 크기를 알아내 대상 파일의 크기를 강제로 조정했다면 두 파일의 크기는 같습니다. 이 상태에서 메모리로 추상화 했기 때문에 메모리 카피는 한 번만 해도 됩니다. 참고하시기 바랍니다. :)
세마포어 개수에 따른 스레드 점유상태
0
61
2
메모리 맵과 비동기 입/출력 조합 #2 수업내용에 질문있습니다.
0
95
2
힙 메모리 블럭 관리 방법 질문
0
97
2
MapViewOfFile 원리 관련 질문있습니다
0
102
1
가상 메모리 시스템 영역 구분
0
96
2
스택 크기 결정 단계
0
75
2
시스템프로그래밍-응용편
0
130
2
바이트와 관련된 유튜브 영상을 못 찾겠어요ㅠㅠ
0
94
2
파일 복사에 관한 질문입니다
0
114
2
세마포어 예제에 대한 질문이 있습니다.
0
110
2
메모장 쓰레기값 ?
0
133
2
64 bit 운영체제라면 가상메모리가
0
180
2
alertable Wait 상태 질문있습니다
0
226
1
GetCurrentDirectory 관련 질문
0
169
2
세마포어 예제중 형변환에 대한 질문
0
162
2
강사님 dll 지연로딩 관련하여 질문 드립니다
0
205
3
선장님 , _beginThreadEx() 함수 원리는 어디서 정보를 얻을 수 있을까요?
0
286
2
메모리 맵 강의 예제의 결과가 이상합니다.
0
227
1
강사님 파일입출력(Callback함수)와 관련하여 질문 드립니다.
0
348
2
dll 명시적 링크 오류 (원인 및 해결 방법이 필요 합니다)
0
966
2
static 영역의 rw 가능한 곳은 어떤 데이터가 담기는지 궁금합니다.
0
223
1
TerminanteProcess 와 관련하여 질문 드립니다.
0
172
1
강사님 스레드 관련 질문 드립니다.
0
226
1
강사님 메뉴얼 중 이것도 궁금해서 여쭤봅니다.
0
210
2





