BASEBALLLLLLLLLLLLLLLLLLLL!!!!!!!!!!!!!!!!!!!!!!!
How To Make A Slot Machine Game In Python

Why is this code faster with Python than with C++?

-1

I wrote a simple code to compare the speed of Python vs. C++. Here is the Python code:

def count_permutations(N:int)->int:
    count=0
    for p in itertools.permutations(range(1,N+1)):
        count += 1
    return count

And here is the C++ code:

int count_permutations(int N) {
    vector<int> v(N);
    iota(v.begin(), v.end(), 1); // fill the vector with 1,...,N
    int count=0;
    do {
        ++count;
    } while ( next_permutation(v.begin(),v.end()) );
    return count;
}

When I run with Python 3.8.5 on Ubuntu, I get:

Permutations of 1..11:
  39916800 permutations calculated in 3.31172251701355 seconds
Permutations of 1..12:
  479001600 permutations calculated in 40.63520336151123 seconds

When I run with C++ (clang++-9) on the same Ubuntu, I get:

Permutations of 1..11:
  39916800 permutations calculated in 5 seconds
Permutations of 1..12:
  479001600 permutations calculated in 57 seconds

I find this very strange, since in the benchmarks website, C++ is always faster than Python.

Is it possible that recent versions of Python have become so fast that they are now faster than their C++ parallel?

Comments

Feed You can follow this conversation by subscribing to the comment feed for this post.

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

Your Information

(Name and email address are required. Email address will not be displayed with the comment.)