C ++代码:

#include <string>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/time.h>

using namespace std;
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

int main() {
    timeval tv1, tv2, tv3, tve;
    gettimeofday(&tv1, 0);
    int size = 0x1000000;
    int fd = open("data", O_RDWR | O_CREAT | O_TRUNC, FILE_MODE);
    ftruncate(fd, size);
    char *data = (char *) mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    for(int i = 0; i < size; i++) {
        data[i] = 'S';
    }
    munmap(data, size);
    close(fd);
    gettimeofday(&tv2, 0);
    timersub(&tv2, &tv1, &tve);
    printf("Time elapsed: %ld.%06lds\n", (long int) tve.tv_sec, (long int) tve.tv_usec);
}


Python代码:

import mmap
import time

t1 = time.time()
size = 0x1000000

f = open('data/data', 'w+')
f.truncate(size)
f.close()

file = open('data/data', 'r+b')
buffer = mmap.mmap(file.fileno(), 0)

for i in xrange(size):
    buffer[i] = 'S'

buffer.close()
file.close()
t2 = time.time()
print "Time elapsed: %.3fs" % (t2 - t1)


我认为这两个程序本质上是相同的,因为C ++和Python调用相同的系统调用(mmap)。

但是Python版本比C ++慢得多:

Python: Time elapsed: 1.981s
C++:    Time elapsed: 0.062143s


谁能解释一下为什么mmap Python比C ++慢得多的原因?



环境:

C ++:

$ c++ --version
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.5.0


蟒蛇:

$ python --version
Python 2.7.11 :: Anaconda 4.0.0 (x86_64)

最佳答案

不是mmap较慢,而是用值填充数组。 Python是众所周知的,它执行原始操作的速度很慢。使用更高级别的操作:

buffer[:] = 'S' * size

关于python - 为什么使用Python mmap模块比从C++调用POSIX mmap慢得多?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38682501/

10-12 17:01
查看更多