Skip to content

Instantly share code, notes, and snippets.

@ivanarrizabalaga
Created March 19, 2015 15:37
Show Gist options
  • Save ivanarrizabalaga/54b43018dd6a10c269bc to your computer and use it in GitHub Desktop.
Save ivanarrizabalaga/54b43018dd6a10c269bc to your computer and use it in GitHub Desktop.
Async logger performance test (simplified)
package ...
import static org.junit.Assert.*
import java.text.MessageFormat
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import org.junit.After;
import org.junit.Before
import org.junit.Test
import ...AcumuladoresTestTools
class TrazadorPromocionesPerformanceTest {
TrazadorPromociones trazadorCarrusel=new TrazadorPromociones()
AcumuladoresTestTools tools=new AcumuladoresTestTools()
private static final int MAX_THREADS=20
private static final int MAX_MSGS_X_THREAD=10000
@Before
@After
void clearLogs() {
//Clear log before & after test
tools.clearLogs()
}
@Test
void muchosThreadsEmitenMuchosMsgs() {
//GIVEN
Cronometro crono=new Cronometro()
crono.start()
//WHEN
runLoggingThreads()
//THEN
crono.stop()
println "Time logging ($MAX_THREADS * $MAX_MSGS_X_THREAD): ${crono.time()} ms."
assertLogTieneLineas(tools.PATH_LOG_EMITIDOS, MAX_MSGS_X_THREAD * MAX_THREADS)
}
/**
* Crea un pool de hilos que esta continuamente emitiendo en el log
*/
private void runLoggingThreads() {
TaskEmision task= new TaskEmision()
ExecutorService pool = Executors.newFixedThreadPool(MAX_THREADS);
for(int i = 0; i < MAX_THREADS; i++){
pool.submit(task);
}
//Espera a que terminen los hilos
pool.shutdown();
try {
//Una vez notificados tiene 30 sec para cerrar
pool.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
}
/**
* Comprueba que el fichero dado tiene el número de lineas indicado
* @param path Path al fichero
* @param numLineasEsperadas Número de lineas esperadas
*/
private void assertLogTieneLineas(String path,int numLineasEsperadas) {
File f=new File(path)
List<String>lineasFichero=f.readLines()
assertEquals("Diferente número de lineas",numLineasEsperadas,lineasFichero.size())
}
/**
* Runnable que emite al log
* @author arrizabalaga
*/
class TaskEmision implements Runnable{
public void run(){
String threadId=Thread.currentThread().getId().toString()
MAX_MSGS_X_THREAD.times {
TrazadorPromociones.emitir MessageFormat.format("thread({0}):{1}",threadId,it+1)
}
}
}
/**
* Clase auxiliar para medir tiempos
* @author arrizabalaga
*/
class Cronometro{
long start
long end
void start() {
start=System.currentTimeMillis()
}
void stop() {
end=System.currentTimeMillis()
}
long time() {
assert start:"No se ha hecho 'start'"
assert end:"No se ha hecho 'stop'"
return end-start
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment