0
0
Rubyprogramming~5 mins

GIL (Global Interpreter Lock) impact in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: GIL (Global Interpreter Lock) impact
O(n)
Understanding Time Complexity

When running Ruby programs that use threads, the Global Interpreter Lock (GIL) affects how fast code runs.

We want to understand how the GIL changes the time it takes when using multiple threads.

Scenario Under Consideration

Analyze the time complexity of this Ruby code using threads.


threads = []
5.times do
  threads << Thread.new do
    1_000_000.times { Math.sqrt(12345) }
  end
end
threads.each(&:join)
    

This code runs 5 threads, each doing a million math calculations, then waits for all to finish.

Identify Repeating Operations

Look at what repeats in the code.

  • Primary operation: The loop inside each thread doing 1,000,000 math calculations.
  • How many times: This loop runs 5 times in parallel threads.
How Execution Grows With Input

Imagine increasing the number of threads or calculations.

Input Size (threads)Approx. Operations
11,000,000 calculations
55,000,000 calculations
1010,000,000 calculations

Normally, more threads mean more work done at once, but the GIL makes threads wait, so total time grows closer to adding work, not speeding it up.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows roughly in direct proportion to the total work, even with multiple threads because the GIL limits true parallel execution.

Common Mistake

[X] Wrong: "Adding more threads always makes the program run faster."

[OK] Correct: The GIL lets only one thread run Ruby code at a time, so threads often wait, limiting speed gains.

Interview Connect

Understanding how the GIL affects threading shows you know how Ruby handles multiple tasks and helps you write better programs that use threads wisely.

Self-Check

"What if the threads mostly run code outside Ruby, like calling system commands? How would the GIL impact change then?"