How do I calculate how many clicks were given in 1 second?
How do I calculate how many clicks were given in 1 second?
First you must capture the click events and put a timestamp for each. For events that inherit from java.awt.event.InputEvent
, this timestamp will be present in the getWhen()
method. .
After collecting a list of clicks, what you should do is something like this, depending on how you want to measure (using java 8 or higher):
public double mediaDeCliquesPorSegundo(Collection<? extends InputEvent> events) {
return mediaPorSegundo(events.stream().map(InputEvent::getWhen).collect(Collectors.toList()));
}
public long cliquesNoUltimoSegundo(Collection<? extends InputEvent> events) {
return noUltimoSegundo(events.stream().map(InputEvent::getWhen).collect(Collectors.toList()));
}
public double mediaPorSegundo(Collection<Long> events) {
long max = events.stream().reduce(Long::max).orElse(0L);
long min = events.stream().reduce(Long::min).orElse(0L);
if (max == min) {
throw new IllegalArgumentException("Precisa de pelo menos dois eventos em tempos diferentes para poder calcular");
}
return events.size() / (double) (max - min);
}
public long noUltimoSegundo(Collection<Long> events) {
long max = events.stream().reduce(Long::max).orElse(0L);
return events.stream().filter(x -> x > max - 1000L).count();
}
If your event class is not a subclass of java.awt.event.InputEvent
, you should use one of the mediaDeCliquesPorSegundo
and cliquesNoUltimo
methods. If it is not, after somehow producing a Collection<Long>
containing the timestamps, you must use one of the methods mediaPorSegundo
or noUltimoSegundo
.
If your event class is something specific like MeuEvento
with a getTimestamp
method, you can do something like mediaDeCliquesPorSegundo
and cliquesNoUltimo
methods to get Collection<Long>
:
public double mediaDeMeusCliquesPorSegundo(Collection<? extends MeuEvento> events) {
return mediaPorSegundo(events.stream().map(MeuEvento::getTimestamp).collect(Collectors.toList()));
}
public long meusCliquesNoUltimoSegundo(Collection<? extends MeuEvento> events) {
return noUltimoSegundo(events.stream().map(MeuEvento::getTimestamp).collect(Collectors.toList()));
}