Unusual Speed Difference between Python and C++

后端 未结 17 2063
庸人自扰
庸人自扰 2020-12-22 21:25

I recently wrote a short algorithm to calculate happy numbers in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it.

17条回答
  •  醉梦人生
    2020-12-22 21:49

    
    #!/usr/bin/env python
    
    import timeit
    
    upperBound = 0
    
    def calcMain():
        known = set()
        for i in xrange(0,upperBound+1):
            next = False
            current = i
            history = set()
            while not next:
                squaresum=0
                while current > 0:
                    current, digit = divmod(current, 10)
                    squaresum += digit * digit
                current = squaresum
                if current in history:
                    next = True
                    if current == 1:
                        known.add(i)
                history.add(current)
    
    while True:
        upperBound = input("Pick an upper bound: ")
        result = timeit.Timer(calcMain).timeit(1)
        print result, "seconds.\n"
    

    I made a couple of minor changes to your original python code example that make a better than 16x improvement to the performance of the code. The changes I made took the 100,000 case from about 9.64 seconds to about 3.38 seconds.

    The major change was to make the mod 10 and accumulator changes to run in a while loop. I made a couple of other changes that improved execution time in only fractions of hundredths of seconds. The first minor change was changing the main for loop from a range list comprehension to an xrange iterator. The second minor change was substituting the set class for the list class for both the known and history variables. I also experimented with iterator comprehensions and precalculating the squares but they both had negative effects on the efficiency. I seem to be running a slower version of python or on a slower processor than some of the other contributers. I would be interest in the results of someone else's timing comparison of my python code against one of the optimized C++ versions of the same algorithm. I also tried using the python -O and -OO optimizations but they had the reverse of the intended effect.

提交回复
热议问题