Skip to content

Instantly share code, notes, and snippets.

@fnovoac
Created June 28, 2018 17:32
Show Gist options
  • Save fnovoac/7499ae56ac226a6e66a9ec2af3d2c64b to your computer and use it in GitHub Desktop.
Save fnovoac/7499ae56ac226a6e66a9ec2af3d2c64b to your computer and use it in GitHub Desktop.
//From: https://github.com/cgoldberg/netplot/blob/0cdac581460f70a3d39929ffb5a2635a9eb16320/src/Stopwatch.java
/*
* Copyright 2006 Corey Goldberg (cgoldberg _at_ gmail.com)
*
* This file is part of NetPlot.
*
* NetPlot is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* NetPlot is distributed in the hope that it will be useful,
* but without any warranty; without even the implied warranty of
* merchantability or fitness for a particular purpose. See the
* GNU General Public License for more details.
*/
public class Stopwatch {
private long startTime = 0;
private long stopTime = 0;
private boolean running = false;
public void start() {
this.startTime = System.currentTimeMillis();
this.running = true;
}
public void stop() {
this.stopTime = System.currentTimeMillis();
this.running = false;
}
// elaspsed time in milliseconds
public long getElapsedTime() {
if (running) {
return System.currentTimeMillis() - startTime;
}
return stopTime - startTime;
}
// elaspsed time in seconds
public long getElapsedTimeSecs() {
if (running) {
return ((System.currentTimeMillis() - startTime) / 1000);
}
return ((stopTime - startTime) / 1000);
}
// sample usage
public static void main(String[] args) {
Stopwatch s = new Stopwatch();
s.start();
// code you want to time goes here
s.stop();
System.out.println("elapsed time in milliseconds: " + s.getElapsedTime());
}
/*
final int MSG_START_TIMER = 0;
final int MSG_STOP_TIMER = 1;
final int MSG_UPDATE_TIMER = 2;
Stopwatch timer = new Stopwatch();
final int REFRESH_RATE = 100;
Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_START_TIMER:
timer.start(); //start timer
mHandler.sendEmptyMessage(MSG_UPDATE_TIMER);
break;
case MSG_UPDATE_TIMER:
tvTextView.setText(""+ timer.getElapsedTime());
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER,REFRESH_RATE); //text view is updated every second,
break; //though the timer is still running
case MSG_STOP_TIMER:
mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates.
timer.stop();//stop timer
tvTextView.setText(""+ timer.getElapsedTime());
break;
default:
break;
}
}
};
public void onClick(View v) {
if(btnStart == v)
{
mHandler.sendEmptyMessage(MSG_START_TIMER);
}else
if(btnStop == v){
mHandler.sendEmptyMessage(MSG_STOP_TIMER);
}
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment