Skip to content

Instantly share code, notes, and snippets.

@dydx
Last active January 26, 2016 15:34
Show Gist options
  • Save dydx/93989cbf21ae36320478 to your computer and use it in GitHub Desktop.
Save dydx/93989cbf21ae36320478 to your computer and use it in GitHub Desktop.
loosely comparing blocking vs non-blocking
$> time node sandwich.js
-> making a burger for marc
-> making a pb&j for mike
-> making a reuben for shawn
<- shawn's reuben is ready in 1399ms
<- mike's pb&j is ready in 1478ms
<- marc's burger is ready in 3327ms
node sandwich.js 0.08s user 0.02s system 2% cpu 3.431 total
$> time node sandwich.js
-> making a burger for marc
-> making a pb&j for mike
-> making a reuben for shawn
<- marc's burger is ready in 624ms
<- shawn's reuben is ready in 4622ms
<- mike's pb&j is ready in 4796ms
node sandwich.js 0.09s user 0.02s system 2% cpu 4.906 total
'use strict';
const order_sandwich = (customer, description, duration) => {
console.log(`-> making a ${description} for ${customer}`);
setTimeout(() => {
console.log(`<- ${customer}'s ${description} is ready in ${duration}ms`);
}, duration);
}
const customers = ["marc", "mike", "shawn"];
const sandwiches = ["burger", "pb&j", "reuben"];
// javascript doesnt have a `zip` function, so we have to
// hack something like this together
const orders = {};
for(let i = 0; i < customers.length; i++) {
orders[customers[i]] = sandwiches[i];
}
for(let customer in orders) {
order_sandwich(customer, orders[customer], Math.floor(Math.random() * 10000));
}
def order_sandwich(customer, description, duration)
puts "-> making a #{description} for #{customer}"
sleep duration
puts "<- #{customer}'s #{description} is ready in #{duration}s"
end
def rand_time
(Random.rand * 10).floor
end
customers = ["marc", "mike", "shawn"].shuffle
sandwiches = ["burger", "pb&j", "reuben"].shuffle
customers.zip(sandwiches).each do |customer, sandwich|
order_sandwich(customer, sandwich, rand_time)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment