Speed Comparison Perl Python & C

Bob Ippolito bob at redivi.com
Sun Feb 29 15:38:31 EST 2004


On 2004-02-29 15:19:52 -0500, Bart Nessux <bart_nessux at hotmail.com> said:

> David Lees wrote:
> 
>> Bart Nessux wrote:
>>> Just fooling around this weekend. Wrote and timed programs in C, Perl and
>>> Python. Each Program counts to 1,000,000 and prints each number to the
>>> console as it counts. I was a bit surprised. I'm not an expert C or Perl
>>> programming expery, I'm most familiar with Python, but can use the others
>>> as well.
>>> 
>>> Here are my results:
>>> 
>>> C = 23 seconds
>>> Python = 26.5 seconds
>>> Perl = 34.5 seconds
>>> 
>>> Here are the programs:
>>> 
>>> -------------------------
>>> #The C version:
>>> -------------------------
>>> 
>>> #include <stdio.h>
>>> 
>>> int main(void)
>>> {
>>> int x = 0;
>>> while (x < 1000000) {
>>> printf("%d \n", x++);
>>> }
>>> }
>>> 
>>> -------------------------
>>> #The Python version:
>>> -------------------------
>>> 
>>> #!/usr/bin/python
>>> 
>>> x = 0
>>> while x < 1000000:
>>> x = x + 1
>>> print x
>>> 
>>> -------------------------
>>> #The Perl version:
>>> -------------------------
>>> 
>>> #!/usr/bin/perl -Tw
>>> 
>>> use strict;
>>> 
>>> my $x = 0;
>>> while($x < 1000000) {
>>> print $x++, "\n";
>>> }
>>> 
>>> What do you guys think of this? I don't know enough about Perl & C, and
>>> perhaps Python, to know if this was indeed a fair test. I thought C would
>>> do this much faster than it did. Any ideas?
>>> 
>>> 
>>> 
>>> 
>> I don't think your times have much to do with the languages.  They are
>> just how long whatever I/O library is used by a particular language
>> takes.  I would guess that the loop overhead is small compared with the
>> I/O formatting and output times in your example.
>> 
>> You should do a Google search on 'Python+benchmarks'.  Benchmarking is
>> tricky and you need to consider what you are trying to compare.
>> 
>> David Lees
> 
> Thanks, I was trying to do something very similar in each language. Just
> wanted to see how fast they could do this, nothing more. I expected the
> order of the results to be c, python and then perl, and I expected c to be
> the *clear* winner. I don't know that much about programming... that's why
> I have all these false notions in my head about speed.

The true notion of speed is that it's relative.  In general, don't 
worry too much about it until it becomes a problem, or until you have a 
lot of free time to go optimizing things that *already work*.  
Premature optimization is just about as bad as it sounds.

-bob




More information about the Python-list mailing list