This decorator limits how often a method can get called in a second.
        If the limit is exceeded, the call will be held in a queue until
        enough time has passed.
        Useful when trying to avoid overloading a system with rapid calls.

def rate_limited(max_per_second):
    """ This decorator limits how often a method can get called in a second.
        If the limit is exceeded, the call will be held in a queue until
        enough time has passed.
        Useful when trying to avoid overloading a system with rapid calls. """
    min_interval = 1.0 / float(max_per_second)

    def decorate(func):
        last_time_called = [0.0]
        rate_lock = threading.Lock()  # To support multi-threading

        def rate_limited_function(*args, **kargs):
            try:
                rate_lock.acquire(True)
                elapsed = time.clock() - last_time_called[0]
                wait_time_remaining = min_interval - elapsed
                if wait_time_remaining > 0:
                    time.sleep(wait_time_remaining)
                last_time_called[0] = time.clock()
            finally:
                rate_lock.release()
            return func(*args, **kargs)
        return rate_limited_function
    return decorate