python - 为什么使用 Python mmap 模块比从 C++ 调用 POSIX mmap 慢得多?

标签 python c++ performance posix mmap

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 :

$ 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/

相关文章:

C++ 强化学习库

c++ - 理解C++应用程序负载均衡

javascript - 放弃(Web 开发)元素文件夹中的子文件夹对性能有好处吗?

c++ - 带有模板化类和派生类的 Swig shared_ptr 宏

c++ - clang 与 gcc 运行时差异 : c++ class template built w clang crashes w/o copy constructor, 使用复制构造函数构建 gcc 崩溃

Python:在不存储项目的情况下获取生成器中的项目数

python - 如何在 xlsxwriter 中将值放置在堆积条形图之外

python - 如何拆分整数并将部分分配给变量

python - pandas 在包含间隔的列中查找值

python - 从旧字典键生成新字典键