Monday, 5 July 2021

Slf4j: profiling

'slf4j-ext' module provides extensions (like profiling, Extended logging, Event logging) to the core slf4j API.

 

In this post, I am going to explain how can we measure application performance using slf4j2 profiling.

 

Step 1: Get an instance of Profiler.

Profiler profiler = new Profiler("Fibonacci test");

 

Step 2: Set the logger to this profiler.

profiler.setLogger(LOGGER);

 

Step 3: Start the profiler before calling the method to monitor.

profiler.start("with recursion");

 

‘start’ method starts a child stop watch and stops any previously started time instruments.

 

Step 4: Stop all the stop watches.

 

TimeInstrument timeInstrument = profiler.stop();


Step 5: Print profiling information.

timeInstrument.print();


Find the below working application.

 

ProfilingDemo.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.profiler.Profiler;
import org.slf4j.profiler.TimeInstrument;

public class ProfilingDemo {

	private static final Logger LOGGER = LoggerFactory.getLogger(ParameterizedLoggingDemo.class);

	private Map<Integer, Integer> internalCache = new HashMap<>();

	public int fibWithDynamicProgramming(int n) {
		if (n < 0) {
			throw new IllegalArgumentException("Fibonaaci can't be calucated for -ve integers");
		}

		return fibWithDynamicProgramming1(n);

	}

	private int fibWithDynamicProgramming1(int n) {
		if (n == 0) {
			return 0;
		}

		if (n == 1) {
			return 1;
		}

		Integer value = internalCache.get(n);

		if (value != null) {
			return value;
		}

		int result = fibWithDynamicProgramming1(n - 1) + fibWithDynamicProgramming1(n - 2);
		internalCache.put(n, result);

		return result;
	}

	public int fibRecursive(int n) {
		if (n == 0) {
			return 0;
		}

		if (n == 1) {
			return 1;
		}

		return fibRecursive(n - 1) + fibRecursive(n - 2);
	}

	public static void main(String args[]) {
		ProfilingDemo demo = new ProfilingDemo();

		Profiler profiler = new Profiler("Fibonacci test");
		profiler.setLogger(LOGGER);

		profiler.start("with recursion");
		demo.fibRecursive(40);

		profiler.start("with Dynamic Programming");
		demo.fibWithDynamicProgramming(40);

		TimeInstrument timeInstrument = profiler.stop();

		timeInstrument.print();

	}

}


Sample Output

+ Profiler [Fibonacci test]
|-- elapsed time         [with recursion]   411.716 milliseconds.
|-- elapsed time [with Dynamic Programming]     0.085 milliseconds.
|-- Total                [Fibonacci test]   412.173 milliseconds.


You can download complete working application from below link.

https://github.com/harikrishna553/java-libs/blob/master/slf4j/slf4j-miscellaneous/src/main/java/com/sample/app/ProfilingDemo.java

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment