Skip to content

Instantly share code, notes, and snippets.

@theherk
Created April 26, 2022 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theherk/27434de0502e874497176dcf299bf76e to your computer and use it in GitHub Desktop.
Save theherk/27434de0502e874497176dcf299bf76e to your computer and use it in GitHub Desktop.
Timing simple slicing vs itertools.pairwise
#!/usr/bin/env python3
from statistics import fmean
import timeit
times_slice = timeit.repeat(
stmt="l = [924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4]; x = l[:-1]; y = l[1:]"
)
times_itertools = timeit.repeat(
stmt="x, y = zip(*pairwise([924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4]))",
setup="from itertools import pairwise",
)
print(f"times with slices: {fmean(times_slice)}")
print(f"times with itertools: {fmean(times_itertools)}")
@theherk
Copy link
Author

theherk commented Apr 26, 2022

Based on this question: https://stackoverflow.com/q/72018286/2081835.

Outputs are:

times with slices: 0.17377224136143923
times with itertools: 0.8396673248615116

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment