All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dk.cooldev.timing.TimeMarker Maven / Gradle / Ivy

The newest version!
package dk.cooldev.timing;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cvwj on 07/08/14.
 */
public class TimeMarker {
    private long start;
    private long end;
    private boolean stopped;
    private long lastMark;

    private List marks = new ArrayList();
    private long duration;

    public TimeMarker() {
        lastMark = start = System.currentTimeMillis();
    }

    public void stop() {
        if (stopped) {
            return;
        }
        end = System.currentTimeMillis();
        stopped = true;
        duration = end - start;
    }

    public void mark(Class clazz, String methodName, String eventName) {
        if (stopped) {
            return;
        }
        long now = System.currentTimeMillis();
        long duration = now - lastMark;
        String name = String.format("%s::%s::%s", clazz.getSimpleName(), methodName, eventName);

        Mark mark = new Mark();
        mark.name = name;
        mark.duration = duration;
        marks.add(mark);
    }

    public long getDuration() {
        if (stopped) {
            return duration;
        } else {
            return System.currentTimeMillis() - start;
        }
    }

    public List getMarks() {
        return marks;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder("{\"duration\":").append(duration).append(", \"marks\":[");
        boolean first = true;
        for (Mark mark : getMarks()) {
            if (first) {
                sb.append("\n").append(mark);
                first = false;
            } else {
                sb.append(",\n").append(mark);
            }
        }
        sb.append("]}");
        return sb.toString();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy