Skip to content

Instantly share code, notes, and snippets.

@kinow
Created February 21, 2018 05:29
Show Gist options
  • Save kinow/c0873daf069c2e64bc69d6305400e610 to your computer and use it in GitHub Desktop.
Save kinow/c0873daf069c2e64bc69d6305400e610 to your computer and use it in GitHub Desktop.
Playing with the StackWatch from Commons Lang
package example;
// imports
class Example {
public static void main(String[] args) throws Exception {
// Travelling to Japan
StackWatch tripWatch = new StackWatch("TripToJapan");
// start trip to Japan
tripWatch.start();
// then start trip part in Tokyo
tripWatch.startTiming("Tokyo", "city");
// go to akihabara
tripWatch.startTiming("Akihabara", "manga", "robots");
Thread.sleep(RandomUtils.nextLong(100, 3000));
tripWatch.stopTiming();
// go to shinjuku
tripWatch.startTiming("Shinjuku", "manga", "izakaya");
Thread.sleep(RandomUtils.nextLong(500, 2000));
tripWatch.stopTiming();
// then stop tokyo
tripWatch.stopTiming();
// then start trip part in Osaka
tripWatch.startTiming("Osaka", "city");
Thread.sleep(RandomUtils.nextLong(200, 6000));
tripWatch.stopTiming();
// then start trip part in Kumamoto
tripWatch.startTiming("Kumamoto", "city");
Thread.sleep(RandomUtils.nextLong(100, 500));
tripWatch.stopTiming();
// then end trip
tripWatch.stop();
// now visit printing each node's level and duration
System.out.println("######## All ########");
tripWatch.visit(new TimingRecordNodeVisitor() {
public void visitRecord(int level, TimingRecordNode node) {
System.out.println("Visit node: " + node.getPath() + " level " + level + " and duration "
+ node.getStopWatch().getNanoTime());
}
});
System.out.println("######## Cities ########");
// or use tags and print just the duration of each city
tripWatch.visit(new TimingRecordNodeVisitor() {
public void visitRecord(int level, TimingRecordNode node) {
String[] tags = node.getTags();
if (tags != null && tags.length > 0) {
for (String tag : tags) {
if (tag.trim().equalsIgnoreCase("city")) {
System.out.println("Visit node: " + node.getPath() + " level " + level + " and duration "
+ node.getStopWatch().getNanoTime());
}
}
}
}
});
}
}
@kinow
Copy link
Author

kinow commented Feb 21, 2018

Outputs:

######## All ########
Visit node: TripToJapan level 0 and duration 4754369797
Visit node: TripToJapan/Tokyo level 1 and duration 2549423016
Visit node: TripToJapan/Tokyo/Akihabara level 2 and duration 1334102112
Visit node: TripToJapan/Tokyo/Shinjuku level 2 and duration 1184098898
Visit node: TripToJapan/Osaka level 1 and duration 1837200357
Visit node: TripToJapan/Kumamoto level 1 and duration 367448407
######## Cities ########
Visit node: TripToJapan/Tokyo level 1 and duration 2549423016
Visit node: TripToJapan/Osaka level 1 and duration 1837200357
Visit node: TripToJapan/Kumamoto level 1 and duration 367448407

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment