[英]Why is Pythons I/O so much slower than C++?
我已經創建了一些用於在Python和C ++中進行測試的代碼,在其中我從文件中讀取兩個矩陣並打印出一些東西。 似乎Python需要大約兩倍的I / O時間:
$ ./test.sh -i Testing/2000.in -p "C++/read-write-only.out" -n 2
Executing: C++/read-write-only.out -i Testing/2000.in > TMPcurrentFileResult.out
It took 8 seconds for 2 executions
MIN: 4 seconds
MAX: 4 seconds
$ ./test.sh -i Testing/2000.in -p "python Python/read-write-only.py" -n 2
Executing: python Python/read-write-only.py -i Testing/2000.in > TMP..Results.out
It took 16 seconds for 2 executions
MIN: 8 seconds
MAX: 8 seconds
這是我用於Python的代碼:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-i", dest="filename", default="bigMatrix.in",
help="input file with two matrices", metavar="FILE")
(options, args) = parser.parse_args()
def read(filename):
lines = open(filename, 'r').read().splitlines()
A = []
B = []
matrix = A
for line in lines:
if line != "":
matrix.append(map(int, line.split("\t")))
else:
matrix = B
return A, B
def printMatrix(matrix):
for line in matrix:
print "\t".join(map(str,line))
A, B = read(options.filename)
# Do something
printMatrix(B)
這是C ++代碼
#include <sstream>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int getMatrixSize(string filename) {
string line;
ifstream infile;
infile.open (filename.c_str());
getline(infile, line);
return count(line.begin(), line.end(), '\t') + 1;
}
void read(string filename, vector< vector<int> > &A, vector< vector<int> > &B){
string line;
FILE* matrixfile = freopen(filename.c_str(), "r", stdin);
int i = 0, j, a;
while (getline(cin, line) && !line.empty()) {
istringstream iss(line);
j = 0;
while (iss >> a) {
A[i][j] = a;
j++;
}
i++;
}
i = 0;
while (getline(cin, line)) {
istringstream iss(line);
j = 0;
while (iss >> a) {
B[i][j] = a;
j++;
}
i++;
}
fclose (matrixfile);
}
void printMatrix(vector< vector<int> > matrix, int n) {
for (int i=0; i < n; i++) {
for (int j=0; j < n; j++) {
if (j != 0) {
cout << "\t";
}
cout << matrix[i][j];
}
cout << endl;
}
}
int main (int argc, char* argv[]) {
string filename;
if (argc < 3) {
filename = "bigMatrix.in";
} else {
filename = argv[2];
}
int n = getMatrixSize(filename);
vector<int> inner (n);
vector< vector<int> > A(n, inner), B(n, inner), C(n, inner);
read (filename, A, B);
// do something with the matrices
printMatrix(C, n);
return 0;
}
是否有可能使I / O的Python速度與C ++一樣快? 如何改善Python / C ++的I / O?
(我聽說scanf應該比cin更快。為什么應該更快?)
這是包含所有代碼的GIT存儲庫 。
需要一段時間才能啟動python解釋器。 運行測試時,請考慮到這一點。
當您不混合使用C和C ++文件操作例程時,應關閉與stdio的同步。
http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/
cin
和cout
通常應比C語言(關閉同步)更快。
就Python的緩慢性而言,那么,為什么不檢查I / O功能的實現呢?
您必須以任何語言緩沖I / O。
為什么要比較Python和C ++?
Python是一種解釋型語言,而C ++是編譯型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.