在这种情况下,为什么Python比C ++更快?

时间:2014-07-22 19:16:22

标签: python c++ performance io

下面给出了Python和C ++中的程序,它执行以下任务:从stdin读取空格分隔的单词,打印按字符串长度排序的唯一单词以及每个唯一单词到stdout的计数。输出行的格式为:length,count,word。

例如,使用此输入文件(488kB的同义词库) http://pastebin.com/raw.php?i=NeUBQ22T

带格式的输出是:

1 57 "
1 1 n
1 1 )
1 3 *
1 18 ,
1 7 -
1 1 R
1 13 .
1 2 1
1 1 S
1 5 2
1 1 3
1 2 4
1 2 &
1 91 %
1 1 5
1 1 6
1 1 7
1 1 8
1 2 9
1 16 ;
1 2 =
1 5 A
1 1 C
1 5 e
1 3 E
1 1 G
1 11 I
1 1 L
1 4 N
1 681 a
1 2 y
1 1 P
2 1 67
2 1 y;
2 1 P-
2 85 no
2 9 ne
2 779 of
2 1 n;
...

这是C ++中的程序

#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>

bool compare_strlen (const std::string &lhs, const std::string &rhs) {
  return (lhs.length() < rhs.length());
}

int main (int argc, char *argv[]) {
  std::string str;
  std::vector<std::string> words;

  /* Extract words from the input file, splitting on whitespace */
  while (std::cin >> str) {
    words.push_back(str);
  }

  /* Extract unique words and count the number of occurances of each word */
  std::set<std::string> unique_words;
  std::map<std::string,int> word_count; 
  for (std::vector<std::string>::iterator it = words.begin();
       it != words.end(); ++it) {
    unique_words.insert(*it);
    word_count[*it]++;
  }

  words.clear();
  std::copy(unique_words.begin(), unique_words.end(),
            std::back_inserter(words));

  // Sort by word length 
  std::sort(words.begin(), words.end(), compare_strlen);

  // Print words with length and number of occurances
  for (std::vector<std::string>::iterator it = words.begin();
       it != words.end(); ++it) {
    std::cout << it->length() << " " << word_count[*it]  << " " <<
              *it << std::endl;
  }

  return 0;
}

以下是Python中的程序:

import fileinput
from collections import defaultdict

words = set()
count = {}
for line in fileinput.input():
  line_words = line.split()
  for word in line_words:
    if word not in words:
      words.add(word)
      count[word] = 1
    else:
      count[word] += 1 

words = list(words)
words.sort(key=len)

for word in words:
  print len(word), count[word], word

对于C ++程序,使用的编译器是带有-O3标志的g ++ 4.9.0。

使用的Python版本是2.7.3

C ++程序所花费的时间:

time ./main > measure-and-count.txt < ~/Documents/thesaurus/thesaurus.txt

real    0m0.687s
user    0m0.559s
sys     0m0.123s

Python程序所用的时间:

time python main.py > measure-and-count.txt < ~/Documents/thesaurus/thesaurus.txt

real    0m0.369s
user    0m0.308s
sys     0m0.029s

Python程序比C ++程序快得多,并且在输入大小较大时相对更快。这里发生了什么?我使用C ++ STL是不正确的?

修改 正如评论和答案所建议的那样,我将C ++程序更改为使用std::unordered_setstd::unordered_map

以下几行已更改

#include <unordered_set>
#include <unordered_map>

...

std::unordered_set<std::string> unique_words;
std::unordered_map<std::string,int> word_count;

编译命令:

g++-4.9 -std=c++11 -O3 -o main main.cpp

这种改善的表现只是轻微的:

time ./main > measure-and-count.txt < ~/Documents/thesaurus/thesaurus.txt

real    0m0.604s
user    0m0.479s
sys     0m0.122s

Edit2: C ++中更快的程序

这是NetVipeC解决方案,DieterLücking的解决方案和this question的最佳答案的组合。真正的性能杀手是cin默认情况下使用无缓冲读取。解决了std::cin.sync_with_stdio(false);。此解决方案还使用单个容器,利用C ++中的有序map

#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>

struct comparer_strlen {
    bool operator()(const std::string& lhs, const std::string& rhs) const {
        if (lhs.length() == rhs.length())
            return lhs < rhs;
        return lhs.length() < rhs.length();
    }
};

int main(int argc, char* argv[]) {
    std::cin.sync_with_stdio(false);

    std::string str;

    typedef std::map<std::string, int, comparer_strlen> word_count_t;

    /* Extract words from the input file, splitting on whitespace */
    /* Extract unique words and count the number of occurances of each word */
    word_count_t word_count;
    while (std::cin >> str) {
        word_count[str]++;
    }

    // Print words with length and number of occurances
    for (word_count_t::iterator it = word_count.begin();
         it != word_count.end(); ++it) {
        std::cout << it->first.length() << " " << it->second << " "
                  << it->first << '\n';
    }

    return 0;
}

运行

time ./main3 > measure-and-count.txt < ~/Documents/thesaurus/thesaurus.txt

real    0m0.106s
user    0m0.091s
sys     0m0.012s

Edit3: Daniel提供了一个简洁的Python程序版本,它与上述版本大致同时运行:

import fileinput
from collections import Counter

count = Counter(w for line in fileinput.input() for w in line.split())

for word in sorted(count, key=len):
  print len(word), count[word], word

运行时:

time python main2.py > measure-and-count.txt.py < ~/Documents/thesaurus/thesaurus.txt

real    0m0.342s
user    0m0.312s
sys     0m0.027s

6 个答案:

答案 0 :(得分:3)

用此测试,它必须比原始C ++更快。

变更是:

  • 删除了向量words以保存单词(将在word_count中保存)。
  • 删除了集unique_words(在word_count中只是唯一的单词)。
  • 将第二个副本删除为单词,不需要。
  • 消除了单词的排序(顺序在地图中更新,现在地图中的单词按长度排序,长度相同的单词按字典顺序排列。

    #include <vector>
    #include <string>
    #include <iostream>
    #include <set>
    #include <map>
    
    struct comparer_strlen_functor {
        operator()(const std::string& lhs, const std::string& rhs) const {
            if (lhs.length() == rhs.length())
                return lhs < rhs;
            return lhs.length() < rhs.length();
        }
    };
    
    int main(int argc, char* argv[]) {
        std::cin.sync_with_stdio(false);
    
        std::string str;
    
        typedef std::map<std::string, int, comparer_strlen_functor> word_count_t;
    
        /* Extract words from the input file, splitting on whitespace */
        /* Extract unique words and count the number of occurances of each word */
        word_count_t word_count;
        while (std::cin >> str) {
            word_count[str]++;
        }
    
        // Print words with length and number of occurances
        for (word_count_t::iterator it = word_count.begin(); it != word_count.end();
             ++it) {
            std::cout << it->first.length() << " " << it->second << " " << it->first
                      << "\n";
        }
    
        return 0;
    }
    

新版本的阅读循环,逐行阅读和分割。需要#include <boost/algorithm/string/split.hpp>

while (std::getline(std::cin, str)) {
    for (string_split_iterator It = boost::make_split_iterator(
             str, boost::first_finder(" ", boost::is_iequal()));
         It != string_split_iterator(); ++It) {
        if (It->end() - It->begin() != 0)
            word_count[boost::copy_range<std::string>(*It)]++;
    }
}

在Core i5,8GB RAM,GCC 4.9.0,32bits中进行测试,运行时间为238ms。已根据建议使用std::cin.sync_with_stdio(false);\n更新了代码。

答案 1 :(得分:2)

进行三项更改,省略额外的向量(在python中没有),为字向量保留内存并避免输出中的endl(!):

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>

bool compare_strlen (const std::string &lhs, const std::string &rhs) {
  return (lhs.length() < rhs.length());
}

int main (int argc, char *argv[]) {
    /* Extract words from the input file, splitting on whitespace */
    /* Also count the number of occurances of each word */
    std::map<std::string, int> word_count;
    {
        std::string str;
        while (std::cin >> str) {
            ++word_count[str];
        }
    }

    std::vector<std::string> words;
    words.reserve(word_count.size());
    for(std::map<std::string, int>::const_iterator w = word_count.begin();
        w != word_count.end();
        ++w)
    {
        words.push_back(w->first);
    }

    // Sort by word length
    std::sort(words.begin(), words.end(), compare_strlen);

    // Print words with length and number of occurances
    for (std::vector<std::string>::iterator it = words.begin();
       it != words.end();
       ++it)
    {
        std::cout << it->length() << " " << word_count[*it]  << " " <<
                  *it << '\n';
    }
    return 0;
}

给出:

原件:

real    0m0.230s
user    0m0.224s
sys 0m0.004s

改进:

real    0m0.140s
user    0m0.132s
sys 0m0.004s

通过添加std::cin.sync_with_stdio(false);更多改进请参阅OregonTrail的问题:

real    0m0.107s
user    0m0.100s
sys 0m0.004s

NetVipeC的std::cin.sync_with_stdio(false);解决方案以及&#39; \ n&#39;替换std :: endl:

real    0m0.077s
user    0m0.072s
sys 0m0.004s

的Python:

real    0m0.146s
user    0m0.136s
sys 0m0.008s

答案 2 :(得分:1)

  std::vector<std::string> words;

  /* Extract words from the input file, splitting on whitespace */
  while (std::cin >> str) {
    words.push_back(str);
  }

这需要在向量增长时不断重复分配/复制/自由操作。预分配矢量或使用类似列表的东西。

答案 3 :(得分:0)

您的C ++代码存在一些问题。

首先,您使用的是可变字符串。这意味着你要围绕一堆复制它们。 (Python字符串是不可变的)。为此测试,我发现效果实际上可以使C ++代码变慢,所以让我们放弃这个。

其次,unordered_容器可能是个好主意。测试这个,我通过交换它们来获得1/3加速(使用boost::hash算法进行散列)。

第三,您在每一行使用std::endl刷新std::cout。这看起来很傻。

Forth,std::cin.sync_with_stdio(false);可以减少std::cin的开销,或者不使用它们。

第五,直接从io构建setmap,不要在std::vector不必要地往返。

这是一个test program(硬编码数据约为大小的1/4),带有不可变字符串(std::shared_ptr<const std::string>)和unordered_容器,带有手动哈希设置,还有一些C ++ 11的功能使代码更短。

删除大型R"(字符串文字,并将stringstream替换为std::cin

为了获得更高的性能,请不要使用重量级的流媒体对象。他们做了很多非常非常偏执的工作。

答案 4 :(得分:0)

这是我认为的另一个C ++版本,我认为它与python逐行匹配。它试图保留python版本中相同类型的容器和操作,并进行明显的C ++特定调整。请注意,我从其他答案中解除了sync_with_stdio优化。

#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <list>

#include <sstream>
#include <iterator>


bool compare_strlen(const std::string &lhs, const std::string &rhs)
{
    return lhs.length() < rhs.length();
}

int main (int argc, char *argv[]) {
    std::unordered_set<std::string> words;
    std::unordered_map<std::string, std::size_t> count;

    // Make std::cin use its own buffer to improve I/O performance.
    std::cin.sync_with_stdio(false);

    // Extract words from the input file line-by-line, splitting on
    // whitespace
    char line[128] = {};  // Yes, std::vector or std::array would work, too.
    while (std::cin.getline(line, sizeof(line) / sizeof(line[0]))) {
        // Tokenize
        std::istringstream line_stream(line);
        std::istream_iterator<std::string> const end;
        for(std::istream_iterator<std::string> i(line_stream);
            i != end;
            ++i) {
            words.insert(*i);
            count[*i]++;
        }
    }

    std::list<std::string> words_list(words.begin(), words.end());
    words_list.sort(compare_strlen);

    // Print words with length and number of occurences
    for (auto const & word : words_list)
        std::cout << word.length()
                  << ' ' << count[word]
                  << ' ' << word
                  << '\n';

    return 0;
}

结果与您原来的python代码和@ NetVipeC的C ++相当。

<强> C ++

real    0m0.979s
user    0m0.080s
sys     0m0.016s

<强>的Python

real    0m0.993s
user    0m0.112s
sys     0m0.060s

我对这个版本的C ++与你的问题的其他简化C ++答案的表现相比有点惊讶,因为我确信基于stringstream的标记化会成为瓶颈。

答案 5 :(得分:-1)

std::setstd::map都针对查找进行了优化,而不是插入。每次更改内容时,必须对它们进行排序/树平衡。您可以尝试使用基于哈希的std::unordered_setstd::unordered_map,并且对您的用例更快。

相关问题