Python Factorial Function Time Test

 · 4 min read
 · shakiestnerd
Table of contents

This article illustrates four ways to calculate a factorial function along with how long each method takes.

I ran across an example factorial calculation in python using a lambda expression on the Make Tech Easier website. It made me wonder how the lambda function compared to using the factorial function that can be found in the math module. So to do a little comparison, I found a couple more examples of factorial calculations from the Progamiz website and wrote some code to measure the execution time for each example.

As a quick refresher, a factorial is the product of all integers less than or equal to an integer n. This is written as n! (the number, followed by an exclamation point). Here are a couple of examples to illustrate the idea.

4! = 4 x 3 x 2 x 1 = 24

10! = 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 3,628,800

As you can guess, the factorial for a function grows really big, really fast.Calculating a factorial is a great test for a programming language.

Below are four examples of calculating a factorial with the python programming language. Here we calculate 500! using four different methods.

The Four Example Methods

  1. Calculate factorial using the reduce() function with a python lambda statement. The reduce() function is from the python functools module.
  2. Calculate using the factorial() function from the python math module.
  3. Calculate using a recursive function.
  4. Calculate using a for loop. Note: This is the slowest way to do it.
import time
from functools import reduce
from math import factorial


def factorize(x: int) -> int:
    """This is a recursive function
    to find the factorial of an integer"""

    if x == 1:
        return 1
    else:
        # recursive call to the function
        return x * factorize(x - 1)


# We will do the factorial of x = 500
x = 500

# Example 1
start = time.time()
for _ in range(10000):
    fact = reduce(lambda a, b: a * b, range(1, x + 1))
end = time.time()
exec1 = end - start
print(f"reduce lambda execution time: {exec1}")

# Example 2
start = time.time()
for _ in range(10000):
    factorial(x)
end = time.time()
exec2 = end - start
print(f"factorial execution time: {exec2}")

# Example 3
start = time.time()
for _ in range(10000):
    factorize(x)
end = time.time()
exec3 = end - start
print(f"factorize recursive execution time: {exec3}")

# Example 4
start = time.time()
factor = 1  # initialize the factor to 1
# Note: this version only runs 1,000 times instead of 10,000
# otherwise, you'ld be here all day waiting for it to finish.
for _ in range(1000):
    for i in range(1, x + 1):
        factor = factor * i
end = time.time()
exec4 = end - start
print(f"factor for loop execution time: {exec4}")

# print(f"factorial is {exec1/exec2} times faster than reduce lambda.")

This captures a start and end time to see how long each step runs. Here are the time results from when I ran it.

  1. reduce lambda execution time: 0.4545600414276123 - 2nd place
  2. factorial execution time: 0.054924726486206055 - 1st place
  3. factorize recursive execution time: 0.6734292507171631 - 3rd place
  4. factor for loop execution time: 22.071449041366577 (1,000 iterations instead of 10,000) also ran

Running the factorial function from the math module was significantly faster. This finding generally holds true for python. If you can leverage a function from one of the optimized modules written in C, you're going to get much better performance. If you have more sophisticated calculation needs, take a look at numpy and scipy.