Skip to content

Instantly share code, notes, and snippets.

@bernEsp
Last active December 18, 2015 18:59
Show Gist options
  • Save bernEsp/5829276 to your computer and use it in GitHub Desktop.
Save bernEsp/5829276 to your computer and use it in GitHub Desktop.
Adding value to the top of array and to the top of linked list benchmarking
Node = Struct.new(:value, :next)
list = Node.new("first", nil)
#create linked list
def linked_list(value, next_node)
Node.new(value, next_node)
end
def unlinked_list(node_value, list)
list = list.next if list.value == node_value
nlist = list
until nlist.next.nil?
if nlist.next.value == node_value
nlist.next = nlist.next.next
break
end
nlist = nlist.next
end
list
end
#stack LIFO in linked link
def pop(list)
return nil if list.nil?
p "deleted #{list.value}"
list = list.next
end
#print values in linked list
def recursive_print(list)
p list.value
recursive_print(list.next) unless list.next.nil?
end
def bench(type)
t1 = Time.now
yield
t2 = Time.now
p "#{type}'s took #{t2-t1}s"
end
################tests############
bench ("array"){
100000.times{ a.insert 0, 10 }
}
=> "array's took 43.453561s"
i=0
bench("linked list"){
100000.times{
list = linked_list(i, list)
i+=1
}
}
=> "linked list's took 0.092356s"
i=9999
bench("unlinked list"){
9999.times{
list = unlinked_list(i, list)
i-=1
}
}
=> "unlinked list's took 16.970523s"
#stack linked list pop node
bench("stack pop list"){
100000.times{
list = pop(list)
}
}
=> "stack pop linked list's took 1.624593s"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment