Page 1 of 6 123 ... LastLast
Results 1 to 10 of 51

Thread: Comparing C++ to Python

  1. #1
    Join Date
    Oct 2006
    Location
    Austin, Texas
    Beans
    2,715

    Comparing C++ to Python

    Ok, I am going to stand on this line in this one, I actually use C++ and Python both a lot. I refuse to favor either of them *generally*

    However, I've seen a lot of people argue that many interpreted languages can compete with the speed of C++, even with graphical program... And I have to say, particularly when it comes to OpenGL graphical programs like games and such, I disagree. I am not saying that I am right, but I am saying that is my experience. To demonstrate, I would like you to have OpenGL properly installed on your computer (probably via mesa), along with GLUT (probably via freeGLUT). You will also need the python binding to openGL (pyOpenGL). Now, I've written a program that is *almost* identical in each of them. Here is the C++ one...

    Code:
    // !# C++ version
    
    #include <GL/gl.h>
    #include <GL/glu.h>
    #include <GL/glut.h>
    
    #include <stdlib.h>
    
    class particle{public:
     float x, y, z;
     particle(){x=(rand()%200-100)*.01; y=(rand()%200-100)*.01; z=(rand()%200-100)*.01;};
     void draw(){
      glVertex3f(x, y, z);
      }
     };
    
    void scene(){
     particle system[10000];
     float angle = 0.0;
     while(true){
      glLoadIdentity();
      glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
      glTranslatef(0.0,0.0,-5.0);
      glRotatef(angle,1.0,1.0,0.0);
      glBegin(GL_POINTS);
      for(int i=0; i< 10000; i++){system[i].draw();}
      glEnd();
      angle += 0.25;
      glutSwapBuffers();
      }
     }
    
    int main(int argc, char** argv) {
     glutInit(&argc, argv);
     glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
     glutInitWindowSize(640, 480);
     glutCreateWindow("Python & OpenGL Demo");
     glEnable(GL_DEPTH_TEST);
     glViewport(0, 0, 640, 480);
     glMatrixMode(GL_PROJECTION);
     glLoadIdentity();
     gluPerspective(45.0, 1.33, 0.1, 100.0);
     glMatrixMode(GL_MODELVIEW);
     glutDisplayFunc(scene);
     glutMainLoop();
     }
    And here is the Python one...
    Code:
    #!/usr/bin/env python
     
    from OpenGL.GL import *
    from OpenGL.GLUT import *
    from OpenGL.GLU import *
    import sys
    import random
    
    class particle:
     def __init__(self):
      self.x = random.uniform(-1, 1)
      self.y = random.uniform(-1, 1)
      self.z = random.uniform(-1, 1)
     def draw(self):
      glVertex3f(self.x, self.y, self.z)
    
    def scene():
     system = []
     angle = 0.0
     for i in range(10000):
      system += [particle()] 
     while 1:
      glLoadIdentity()
      glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT)
      glTranslatef(0.0,0.0,-5.0)
      glRotatef(angle,1.0,1.0,0.0)
      glBegin(GL_POINTS)
      for i in range(10000): system[i].draw()
      glEnd()
      angle += 0.25
      glutSwapBuffers()
     
    def main():
     glutInit(sys.argv)
     glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH)
     glutInitWindowSize(640, 480)
     glutCreateWindow("Python & OpenGL Demo")
     glEnable(GL_DEPTH_TEST)
     glViewport(0, 0, 640, 480)
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     gluPerspective(45.0, 1.33, 0.1, 100.0)
     glMatrixMode(GL_MODELVIEW)
     glutDisplayFunc(scene)
     glutMainLoop()
    main()
    The C++ one can be compiled using "g++ program.cpp -lglut -lGLU -lGL" and executed using "./a.out" from the resulting executable.

    The python one is executed using "python program.py"

    There is no FPS counter because I didn't want to allow for any more variation in the code, but you can easily count rotations-per-minute with a stopwatch. This may just be my computer, but after running this a few times with each I have noticed that the C++ version is considerably faster than the python one. If I am forgetting something, or doing something wrong here, please let me know.

    But, one thing that I also noticed is how similar the code is... Almost identical. Even a non-programmer could look at it and see the same program. The only major differences are the use of lists instead of arrays in the python one, and the use of random is different due to a lack of similarity (this wont affect the speed, the random routine is done BEFORE the rendering loop).

    Anyway, thats all. I just though I would share this. Like I said, I am open to corrections if I went about testing this wrong.

    EDIT:

    btw, this program may be pretty CPU intensive, I creates 10000 particles and then displays them in a loop. You may adjust the number 10000 in each of them to try different speeds. (less=faster, more=slower)
    Last edited by Wybiral; December 11th, 2006 at 08:08 AM.

  2. #2
    Join Date
    Nov 2005
    Location
    Taunton, England
    Beans
    931
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Comparing C++ to Python

    quite cool but alltogether unsuprising. compiled languages are faster than interpreted? colour me intrigued

  3. #3
    Join Date
    Oct 2006
    Location
    Austin, Texas
    Beans
    2,715

    Re: Comparing C++ to Python

    That's what I've always thought, but I have seen people argue themselves blue over the subject. Don't get me wrong though... I love python. I use it a lot, and I certainly wont stop anytime soon. But I love it because it is simple and elegant, not because it is fast. But also... It isn't slow or anything either, 10000 particles is a lot of freaking particles, I'm actually impressed it runs as well as it does!

  4. #4
    Join Date
    Oct 2006
    Location
    Austin, Texas
    Beans
    2,715

    Re: Comparing C++ to Python

    I had an idea, I can eliminate the main difference by using display lists instead of an array or a python list! I almost have to eat my words with this example because they run at nearly equal speeds!!!

    Cpp:
    Code:
    // !# C++ version
    
    #include <GL/gl.h>
    #include <GL/glu.h>
    #include <GL/glut.h>
    
    #include <stdlib.h>
    
    void scene(){
     float angle = 0.0;
     glNewList(1, GL_COMPILE);
     glBegin(GL_POINTS);
     for(int i=0; i< 20000; i++)
      glVertex3f((rand()%200-100)*.01, (rand()%200-100)*.01, (rand()%200-100)*.01);
     glEnd();
     glEndList();
     while(true){
      glLoadIdentity();
      glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
      glTranslatef(0.0,0.0,-5.0);
      glRotatef(angle,1.0,1.0,0.0);
      glCallList(1);
      angle += 0.25;
      glutSwapBuffers();
      }
     }
    
    int main(int argc, char** argv) {
     glutInit(&argc, argv);
     glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
     glutInitWindowSize(640, 480);
     glutCreateWindow("Python & OpenGL Demo");
     glEnable(GL_DEPTH_TEST);
     glViewport(0, 0, 640, 480);
     glMatrixMode(GL_PROJECTION);
     glLoadIdentity();
     gluPerspective(45.0, 1.33, 0.1, 100.0);
     glMatrixMode(GL_MODELVIEW);
     glutDisplayFunc(scene);
     glutMainLoop();
     }
    Python:
    Code:
    #!/usr/bin/env python
     
    from OpenGL.GL import *
    from OpenGL.GLUT import *
    from OpenGL.GLU import *
    import sys
    import random
    
    def scene():
     angle = 0.0
     glNewList(1, GL_COMPILE)
     glBegin(GL_POINTS)
     for i in range(20000):
      glVertex3f(random.uniform(-1, 1), random.uniform(-1, 1), random.uniform(-1, 1))
     glEnd()
     glEndList()
     while 1:
      glLoadIdentity()
      glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT)
      glTranslatef(0.0,0.0,-5.0)
      glRotatef(angle,1.0,1.0,0.0)
      glCallList(1)
      angle += 0.25
      glutSwapBuffers()
     
    
    
    def main():
     glutInit(sys.argv)
     glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH)
     glutInitWindowSize(640, 480)
     glutCreateWindow("Python & OpenGL Demo")
     glEnable(GL_DEPTH_TEST)
     glViewport(0, 0, 640, 480)
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     gluPerspective(45.0, 1.33, 0.1, 100.0)
     glMatrixMode(GL_MODELVIEW)
     glutDisplayFunc(scene)
     glutMainLoop()
    main()
    BTW, I've upped the stakes to displaying 20000 particles instead of 10000 because of the speed increase from using display lists.

    The only problem here is that scenes are not alway capable of being precompiled like this. So, while this example may be identical speeds, this does not apply to every program, and considering the use of non-compiled scenes is probably more common (unless you are always planning to use static scenes) I would still have to vote that C++ will be faster most of the time.

    But it is very interesting how fast python is able to run an OpenGL program like this.

  5. #5
    Join Date
    Nov 2005
    Location
    Taunton, England
    Beans
    931
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Comparing C++ to Python

    no matter which way you turn it, identical code in an interpreted language will be at best nearly the same speed as c++

    if speed is your game, c++ is your tool. there is a reason why something like 95% of modern commercial games are written in c++

  6. #6
    Join Date
    Jan 2006
    Beans
    Hidden!
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: Comparing C++ to Python

    Wybiral, thank you for the testing ...

    so, what results did you get? I personally wouldn't mind dropping 5% perfomance for easier editing. Also, try compiling the python code, let's see what that does.

  7. #7
    Join Date
    Dec 2005
    Location
    Lund, Skåne
    Beans
    580

    Re: Comparing C++ to Python

    Now this tells you something more interesting.

    Given how equal the code is, it's probably worth it to prototype _everything_ in python, then move finished bits of the OpenGL app to C++

    And, did you run this code with Psycho (a Python optimizer/thing)

    I write Kupfer, a smart, quick launcher.
    Recommended apps and tools: Vim!

  8. #8
    Join Date
    Oct 2006
    Location
    Austin, Texas
    Beans
    2,715

    Re: Comparing C++ to Python

    Well, on my computer the example that did NOT use display list's (as in the openGL rendering was all realtime, display lists precompile the scene to increase speed) I had almost TWICE the speed with C++ (I counted about 2 times more rotations than the python script per minute). I am curious how it runs on other computers and with other versions of python if someone would like to test it.

    I am using 2.5 for the record. Now... With the display lists added, I had an almost equal count every time (give or take a few) and I would say that with static scenes, using display lists, you will probably not see any speed decrease at all (probably due to the fact that OpenGL will be handling the entire process rather than the language).

    While I didn't do any FPS calculating (I didn't want to ruin the purity of the experiment with FPS counting routines) I can say that python is still pretty good at handling OpenGL with pyOpenGL. It ran very smoothly even with the butt-load of particles I was making it render. And with the use of display list's... Forget about it... Very nice frame-rate on my end. But, I still have to say, if you demand maximum speed, C++ is probably the way to go. But, if speed isn't a huge issue, python for sure.

    Python is very easy to write things like this in... However, for anyone afraid to use C++ who is overly comfortable with python, this example speaks for itself, the code for each is almost identical! Paste each of them to a file and set them up next to each other... Its really weird to look at in my opinion.

    EDIT:

    Nope, it was just plain old python. I haven't messed with any optimizers or anything yet. And it was not compiled or anything like that, just "python program.py"

  9. #9
    Join Date
    Jan 2006
    Beans
    Hidden!
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: Comparing C++ to Python

    well, why not make a specific number of loop iterations and then use the time function ...

  10. #10
    Join Date
    Jun 2006
    Location
    CT, USA
    Beans
    5,267
    Distro
    Ubuntu 6.10 Edgy

    Re: Comparing C++ to Python

    Quote Originally Posted by Choad View Post
    no matter which way you turn it, identical code in an interpreted language will be at best nearly the same speed as c++

    if speed is your game, c++ is your tool. there is a reason why something like 95% of modern commercial games are written in c++
    I'll bite. Of course raw speed is better in C++. I agree 100%. Let me play the devil's advocate (or the angel's, or the python's ): why you could *still* be better off using "slower" python?

    1. Speed-to-market might be more important than processing speed. If you are in the startup, having your killer app out on the market 3 months ahead of the competition, and being able match features of your competitors within a week, might be more important. If your application scales well, as you gain users you can dump more cheap servers to run it. Thats what Google does. Google also employs many top-level Python hackers, including Guido and Alex Martelli.
    2. Save speed by implementing efficent design, not by optimizing loops and function calls. Agile language like python allows you to try multiple approaches, refactor quickly, and still have functioning code.
    3. Find bottlenecks and optimize only those - maybe even reimplement them in C. You may find out that 90% of the time is spent in 5% of the code. If python allows you to develop code 10 times faster, it would be waste of time to implement 95% of non-critical code in C/C++, and premature optimization. Speed is not a problem until it is a problem. And we know that premature optimization is root of all evil.
    4. use NumPy module for fast calculations on big matrices, implemented in C (runs with speed of C).
    5. Maintenance cost and cost of adding new functions. I read recently that with operating environment changing quickly, companies might need to change internal process every 2 years. Having flexible IT infrastucture allowing that is crucial.


    I actually like C. I coded in assembler before and with C, I really love the feeling what it generates efficient binary for me. It is doing what I would do in assembler. But in python I am just so much more productive...
    Last edited by pmasiar; December 11th, 2006 at 02:40 PM.

Page 1 of 6 123 ... LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •