technology
algorithms
performance
benchmarking
datastructures
Ask anything about this article
Hi! I've read this article.
What would you like to know?
@farhan

| Algorithm | Time (worst) | Space (worst) | Typical Use Case |
|---|---|---|---|
| Binary Search | O(log n) | O(1) | Searching sorted arrays |
| Dijkstra (binary‑heap) | O((V+E) log V) | O(V) | Shortest path in weighted graphs |
While the asymptotic bounds give a first impression, they hide constants that matter in practice. For example, binary search performs a single comparison per loop iteration, but branch misprediction can add latency on modern CPUs.
timeit module to measure wall‑clock time for representative inputs. All benchmarks run on a 3.2 GHz Intel i7 with Python 3.11.pythondef binary_search(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
pythonimport heapq
def dijkstra(graph, start):
dist = {node: float('inf') for node in graph}
dist[start] = 0
pq = [(0, start)]
while pq:
d, u = heapq.heappop(pq)
if d != dist[u]:
continue
for v, w in graph[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd
heapq.heappush(pq, (nd, v))
return dist
pythonimport random, timeit
# Binary search data
sorted_list = list(range(0, 10_000_000, 2))
target = 9_999_998
# Dijkstra data (sparse random graph)
V = 10_000
E = 30_000
graph = {i: [] for i in range(V)}
for _ in range(E):
u = random.randrange(V)
v = random.randrange(V)
w = random.randint(1, 20)
graph[u].append((v, w))
bs_time = timeit.timeit('binary_search(sorted_list, target)', globals=globals(), number=100)
print('Binary search avg ms:', (bs_time/100)*1000)
d_time = timeit.timeit('dijkstra(graph, 0)', globals=globals(), number=5)
print('Dijkstra avg ms:', (d_time/5)*1000)
cProfile we see that binary search spends >99 % of its time in the tight loop with negligible function call overhead. Dijkstra's hot spots are the heap operations (heapq.heappush/pop) and edge relaxation.