Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //compilation: g++ -O3 -Wall mmap_test.cpp
- //run:
- // time ./a.out large_file 0 #mmap test
- // time ./a.out large_file 1 #fread test
- //3Gb file generation:
- // python -c "s = 'x'*(2**27); f = open('large_file', 'wb'); [f.write(s) for i in xrange(3*8)]; f.close()"
- //
- //
- #include <sys/types.h>
- #include <sys/mman.h>
- #include <sys/stat.h>
- #include <sys/stat.h>
- #include <stdio.h>
- #include <stdlib.h>
- void fatal(const char *msg) {
- fprintf(stderr, "%s\n", msg);
- exit(1);
- }
- off_t file_length(FILE *f) {
- struct stat stat_buf;
- if (fstat(fileno(f), &stat_buf) == -1)
- fatal("file_length failed");
- return (stat_buf.st_size);
- }
- const unsigned char *mmapfile1(const char *filename, off_t *n) {
- FILE *f = fopen(filename, "rb");
- if (!f) fatal("can't open file");
- *n = file_length(f);
- void *p = mmap(NULL, *n, PROT_READ, MAP_PRIVATE, fileno(f), 0);
- if (p == MAP_FAILED)
- fatal("mmap failed");
- return (const unsigned char*)p;
- }
- const unsigned char *mmapfile2(const char *filename, off_t *n) {
- FILE *f = fopen(filename, "rb");
- if (!f) fatal("can't open file");
- *n = file_length(f);
- unsigned char *buf = new unsigned char[*n];
- if (*n != (off_t)fread(buf, 1, *n, f))
- fatal("fread failed");
- return buf;
- }
- int main(int argc, char **argv) {
- if(argc != 3)
- fatal("invalid cmd line, expected filename and mmmap-type (0/1)");
- long long int s = 0;
- {
- off_t n;
- bool which_mmap = (argv[2][0] == '0');
- const char *filename = argv[1];
- const unsigned char *data = (which_mmap ? mmapfile1 : mmapfile2)(filename, &n);
- printf("%lld\n", (long long int)n);
- printf("%p\n", data);
- for(off_t i = 0; i<n; i += 1024) {
- s += (unsigned char)data[i];
- }
- }
- printf("s: %lld\n", s); //verify, that all data is really loaded (no lazy optimizations)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement