/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.events;

import java.util.concurrent.Semaphore;
import net.ranides.assira.time.TimeStack;
import net.ranides.assira.time.TimeUtils;

/**
 * Measure overhead of creation and running many threads.
 * 
 * CREATE:  4000 threads in 325 ms
 * EXECUTE: 4000 threads in 840 ms
 * 
 * SUMMARY:
 *      12'000 threads / s
 *      16'000 threads / s on my old PC (George)
 * 
 *       4'750 semaphores / s
 * 
 * CONCLUSION:
 *      threading overhead is overestimated
 *      if acceptable overhead is ~1% then 
 *      we should use ThreadPool for more than 100 threads / s
 * 
 * @author ranides
 */
public class ThreadBenchmark {
    
    @SuppressWarnings("PMD.SystemPrintln")
    public static void main(String[] args) throws InterruptedException {
        TimeStack tsm = new TimeStack();
        final Semaphore count = new Semaphore(Integer.MAX_VALUE, true);

        tsm.start(2);
        
        for(int i=0; i<4000; i++) {
            count.tryAcquire();
            new Thread() {
                @Override
                public void run() {
                    TimeUtils.sleep(500);
                    count.release();
                }
            }.start();
        }
        
        // około 16000 wątków / s
        
        System.out.println("\ncreation = " + tsm.stop());
        count.acquire(Integer.MAX_VALUE);
        System.out.println("\nexecution = " + tsm.stop());
        
    }
    
}
