Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any real examples to show python's inefficiency? [closed]

It is always said that Python is not so efficient as other languages such as C/C++, Java etc. And it is also recommended to write the bottleneck part in C. But I've never run into such problems, maybe it's because most of the time it is the way you solve the problem rather than the efficiency of the language to bother.

Can anybody illustrate any real circumstances? Some simple codes will be great.

like image 336
Shady Xu Avatar asked Jun 12 '13 08:06

Shady Xu


People also ask

Why is Python inefficient?

Unlike other popular programming languages including C# or JAVA, Python is dynamically typed and an interpreted language. It is slow primarily due to its dynamic nature and versatility.

Are for loops inefficient?

Indeed, R for loops are inefficient, especially if you use them wrong.


2 Answers

There is already an answer to this on SO: Is Python faster and lighter than C++?. It references the Computer Languages Benchmarks Game which I wanted to cite here in the first place.

So Python is (when not using built-in C-code) a lot slower when it comes to doing serious computations.

like image 84
Sebastian Avatar answered Nov 03 '22 02:11

Sebastian


A practical comparison using insertion sort, as you can see C is much faster. Note that these are attempts at a 1-to-1, in the real world you would just use Python's sort which uses https://en.wikipedia.org/wiki/Timsort and is far more efficient. Results:

Python

real  0m0.034s
user  0m0.028s
sys   0m0.008s

C

real  0m0.003s
user  0m0.000s
sys   0m0.000s

First in Python

#!/usr/bin/python

a = [16, 7, 4, 10, 18, 15, 6, 12, 13, 5, 11, 14, 17, 8, 2, 9, 19, 3, 1]
print 'Unsorted: %s' % a

def insertion_sort(a):
    for j in range(1, len(a)):
        key = a[j]
        i = j - 1
        while i >= 0 and a[i] > key:
        a[i+1] = a[i]
        i = i - 1
    a[i+1] = key
    return a

# execute the sort
print 'Sorted: %s' % insertion_sort(a)

second in C

#include <stdio.h>
#include <stdlib.h>

/*
    Compile with: 

    cc insertion-sort.c -o insertion-sort
*/
int main(int argc, char **argv) 
{
   int a[20] = {16, 7, 4, 10, 18, 15, 6, 12, 13, 5, 11, 14, 17, 8, 2, 9, 20, 19, 3, 1};
   int i, j, key;
   int len = 20;

   printf("Unsorted: [");
   for ( i = 0; i < len; i++ ) {
       printf(" %d ", a[i]);
   }
   printf("]\n");

   for ( j = 0 ; j < len ; j++ ) 
   {
       key = a[j];
       i = j - 1;
       while ( i >= 0 && a[i] > key ) {
           a[i + 1] = a[i];
           i = i - 1;
       }    
       a[i + 1] = key;
   }

   printf("Sorted: [");
   for ( i = 0; i < len; i++ ) {
       printf(" %d ", a[i]);
   }
   printf("]\n");
}
like image 32
igniteflow Avatar answered Nov 03 '22 01:11

igniteflow