Pourquoi lire des lignes de stdin beaucoup plus lent en C+ que Python

Mots clés : pythonc++benchmarkingiostreamgetlinepython

meilleur 5 Réponses Pourquoi lire des lignes de stdin beaucoup plus lent en C+ que Python

vote vote

97

std::ios_base::sync_with_stdio(false); 
int myvalue1; cin >> myvalue1; int myvalue2; scanf("%d",&myvalue2); 
vote vote

81

./a.out < in Saw 6512403 lines in 8 seconds.  Crunch speed: 814050 
CALL                                        COUNT __mac_syscall                                   1 <snip> open                                            6 pread                                           8 mprotect                                       17 mmap                                           22 stat64                                         30 read_nocancel                               25958 
./a.py < in Read 6512402 lines in 1 seconds. LPS: 6512402 
CALL                                        COUNT __mac_syscall                                   1 <snip> open                                            5 pread                                           8 mprotect                                       17 mmap                                           21 stat64                                         29 
vote vote

70

$ /usr/bin/time cat big_file | program_to_benchmark 
$ /usr/bin/time program_to_benchmark < big_file 
$ cat big_file | /usr/bin/time program_to_benchmark 
$ /usr/bin/time sh -c 'cat big_file | program_to_benchmark' 
$ /usr/bin/time cat temp_big_file | wc -l 0.01user 1.34system 0:01.83elapsed 74%CPU ... 
$ /usr/bin/time wc -l < temp_big_file 
$ time wc -l < /tmp/junk real 0.280s user 0.156s sys 0.124s (total cpu 0.280s) $ time cat /tmp/junk | wc -l real 0.407s user 0.157s sys 0.618s (total cpu 0.775s) $ time sh -c 'cat /tmp/junk | wc -l' real 0.411s user 0.118s sys 0.660s (total cpu 0.778s) 
vote vote

69

std::ios_base::sync_with_stdio(false); char buffer[1048576]; std::cin.rdbuf()->pubsetbuf(buffer, sizeof(buffer)); 
vote vote

50

//open file in binary mode std::fstream file( filename, std::ios::in|::std::ios::binary ); if( !file ) return NULL;  //read the size... file.seekg(0, std::ios::end); size_t length = (size_t)file.tellg(); file.seekg(0, std::ios::beg);  //read into memory buffer, then close it. char *filebuf = new char[length+1]; file.read(filebuf, length); filebuf[length] = '\0'; //make it null-terminated file.close(); 
std::istrstream header(&filebuf[0], length); 

Questions similaires