#!/usr/bin/env python
#
# use_resources

'''
Python script to use a certain amount of RAM on disk and number of
threads

Usage:
    use_resources -g <num_gb> -p <num_threads>
'''

# Function to occupy GB of memory
def use_gb_ram(num_gb):
    '''
    Function to consume GB of memory
    '''

    # Eat 1 GB of memory for 1 second
    gb_str = ' ' * int(num_gb*1024.0**3)

    # Spin CPU
    ctr = 0
    while ctr < 30e6:
        ctr+= 1

    # Clear memory
    del ctr
    del gb_str


# Make main executable
if __name__ == '__main__':

    # Import packages
    import argparse
    from threading import Thread
    from multiprocessing import Process

    # Init argparser
    parser = argparse.ArgumentParser(description=__doc__)

    # Add arguments
    parser.add_argument('-g', '--num_gb', nargs=1, required=True,
                        help='Number of GB RAM to use, can be float or int')
    parser.add_argument('-p', '--num_threads', nargs=1, required=True,
                        help='Number of threads to run in parallel')

    # Parse args
    args = parser.parse_args()

    # Init variables
    num_gb = float(args.num_gb[0])
    num_threads = int(args.num_threads[0])

    # Build thread list
    thread_list = []
    for idx in range(num_threads):
        thread_list.append(Thread(target=use_gb_ram, args=(num_gb/num_threads,)))

    # Run multi-threaded
    print('Using %.3f GB of memory over %d sub-threads...' % \
          (num_gb, num_threads))
    for thread in thread_list:
        thread.start()

    for thread in thread_list:
        thread.join()
