Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I'm working on a IRC Twitch.tv BOT (PircBot) and i want to implement a !uptime chatcommand which will display how long the Stream is online.
I searched in google a Bit and i only found solutions which requires a GUI.
Can Some1 tell me what libraries are good to use or give me some exampel code?
I need to display seconds, minutes, hours, days.
First i thought about doing a normal timer which counts +1 all seconds but i think its easier and there are some proper functions to handle such "count"-timers, right?
Im fine with any hints!
thanks :)
Thats what i came up with now:
In my Main class, i got a timer which i call with:
utimecounttimer();
My Timer looks like this:
public void utimecounttimer() {
uptimetimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (isstreamlive == true){
UptimeCount.Uptimestart();
}else{
UptimeCount.Uptimestop();
}
}
}, 1000, 1000);
}
and then my UptimeCount Class is here:
public class UptimeCount {
public static long startTime = 0;
public static long OnlineTimeMillis = 0;
public static float OnlineTimeSec = 0;
public static float OnlineTimeMin = 0;
public static float OnlineTimeHour = 0;
public static float OnlineTimeDay = 0;
public static void Uptimestart(){
if(startTime == 0){
startTime = System.currentTimeMillis();
}else
if(startTime != 0){
OnlineTimeMillis = System.currentTimeMillis()-startTime;
OnlineTimeSec = OnlineTimeMillis /1000F;
OnlineTimeMin = OnlineTimeMillis /(60*1000F);
OnlineTimeHour = OnlineTimeMillis /(60*60*1000F);
OnlineTimeDay = OnlineTimeMillis /(24*60*60*1000F);
}
System.out.println("Seconds"+OnlineTimeSec);
System.out.println("Minutes"+OnlineTimeMin);
System.out.println("Hours"+OnlineTimeHour);
System.out.println("Days"+OnlineTimeDay);
}
public static void Uptimestop(){
startTime = 0;
OnlineTimeMillis = 0;
OnlineTimeSec = 0;
OnlineTimeMin = 0;
OnlineTimeHour = 0;
OnlineTimeDay = 0;
}
}
And then, last but not least il get the Infos in chat with the following line in my Main class:
if (message.equalsIgnoreCase("!uptime")) {
sendMessage(channel," Stream is running for: "+UptimeCount.OnlineTimeDay +" Days, "+UptimeCount.OnlineTimeHour +" Hours. "+UptimeCount.OnlineTimeMin +" Minutes and " +UptimeCount.OnlineTimeSec +" Seconds.");
}
I didnt test it yet but i think i have to format the ms output of the floats and then it should be working, right?
You can use Joda Time to represent durations and times:
// at startup of the stream
DateTime startedAt = DateTime.now();
// later
Duration elapsed = new Duration(startedAt, DateTime.now());
And could use the solution described in this answer to format your output, to get a human readable output (ie. "1 hours 2 minutes").
Please also check Duration since it has methods like toStandardHours, toStandardMinutes which can be used to display the total number of hours/minutes/etc. elapsed (ie. "1 hours | 62 minutes").
// it will give you current time in mille seconds
long startTime = System.currentTimeMillis();
// Mill second diffrence
long OnlineTimeMillis = System.currentTimeMillis()-startTime;
// time diff in mille seconds since you are online
float OnlineTimeSec = OnlineTimeMillis /1000F;
// time diff in Minutes since you are online
float OnlineTimeMin = OnlineTimeMillis /(60*1000F);
// time diff in Hours since you are online
float OnlineTimeHour = OnlineTimeMillis /(60*60*1000F);
// time diff in days since you are online
float OnlineTimeDay = OnlineTimeMillis /(24*60*60*1000F);
Related
I am making a timed quiz where there should be a timer on each question.
I want my code to output a question for 20 seconds and ask for an input for the answer and when the time is up, question number 2 should show up. I am stuck on what should I do to have that, a reference is enough, I just don't know what to read on about, I am using java.util.Timer and TimerTask.
I also tried
ExecutorService but i only see examples that it shutsdown after the timer, i need to post another question after the timer ends, not shotdown the program since i need a time limit for each question and not a timer for the whole quiz.
I tried this
if(seconds<=20)
{
question1();
}
else if (seconds<=40||seconds>=21)
{
new ProcessBuilder("cmd","/c","cls").inheritIO().start().waitFor();
question2();
}
I also tried using while
while(seconds<=20){
question1();
}
while(seconds<=40||seconds>=21){
new ProcessBuilder("cmd","/c","cls").inheritIO().start().waitFor();
question2();
}
This is what my question method looks like.
public static void question2(String... args) throws
IOException, InterruptedException
{
System.out.println("");
System.out.printf("%72s\n","QUIZ FOR PHILIPPINE HISTORY");
System.out.println("");
System.out.printf("%64s\n","Question #2");
System.out.println("");
System.out.println("\t\t\t\t\t WHO DISCOVERED PHILIPPINES?");
System.out.println("\n\t\t\t\t\t\tA. Fernando Magellan");
System.out.println("\t\t\t\t\t\tB. Ferdinand Megallan");
System.out.println("\t\t\t\t\t\tC. Ferdinand Magellan");
System.out.println("\t\t\t\t\t\tD. Fernando Poe");
System.out.println("\n\t\t\t\t\t\tTYPE YOU ANSWER HERE: ");
char answer2 = a.nextLine().charAt(0);
switch (sagot2)
{
case 'B':
case 'b':
score++;
seconds = 21;
System.out.print("You are CORRECT!");
break;
default:
System.out.print("You are WRONG");
seconds = 21;
break;
}
}
This is the beginning of my code plus the timer and timertask.
import java.util.Timer;
import java.util.TimerTask;
import java.util.Scanner;
import java.io.IOException;
public class q2 {
static int seconds = 0;
static Scanner a=new Scanner(System.in);
static Timer timer = new Timer();
static int number = 1;
static int score = 0;
public static void mema(){
TimerTask task = new TimerTask ()
{
public void run()
{
seconds++;
System.out.print(seconds);
}
};
timer.schedule(task,1000,1000);
}
I also tried using this but it doesnt do the other method after 5 seconds.
long start = System.currentTimeMillis();
long wait = 5000;
long end = start + wait;
long end1 = end + wait;
while (System.currentTimeMillis() < end)
{
question1();
}
while (System.currentTimeMillis() < end1 || System.currentTimeMillis() > end)
{
question2();
}
Various things that you did make your code more complicated then it ought to.
First of all, avoid fixing details such as "this is the first question" versus "this is the second question".
Instead: focus on basic elements that you need. In your case: you want to display a question for a certain amount of time. Afterwards, the program should either display another question - or probably give a summary and end.
Thus: write a class/method that simply puts up a question and then waits. And then think how you could re-use that code to put up any number of questions in sequence.
For the "timing": given the fact that you are a beginner, I would recommend you to not go "fully multi-threaded" (meaning: tasks, and schedulers) at this point. Instead, "waiting for some time" can easily be achieved via
getting the currentTime
endTime = currentTime + 20 sec
looping until that endTime is reached
Thing is: you learn programming by exploring your options and trying many things. Thus I gave you hints - not code.
I was in a job interview and got this question: " Write a function that gets 2 strings s,t that represents 2 hours ( in format HH: MM: SS ). It's known that s is earlier than t.
The function needs to calculate how many hours between the two given hours contains at most 2 digits.
For example- s- 10:59:00, t- 11:00:59 -
Answer- 11:00:00, 11:00:01,11:00:10, 11:00:11.
I tried to do while loops and got really stuck. Unfortunately, I didn't pass the interview.
How can I go over all the hours (every second is a new time) between 2 given hours in java as explained above? Thanks a lot
Java 8 allows you to use LocalTime.
LocalTime time1 = LocalTime.parse(t1);
LocalTime time2 = LocalTime.parse(t2);
The logic would require you to count the amount of different digits in a LocalTime, something like
boolean isWinner(LocalTime current) {
String onlyDigits = DateTimeFormatter.ofPattern("HHmmss").format(current);
Set<Character> set = new HashSet<>();
for (int index = 0; index < onlyDigits.length(); index++) {
set.add(onlyDigits.charAt(index));
}
return set.size() <= 2;
}
You can loop between the times like this
int count = 0;
for (LocalTime current = time1; current.isBefore(time2); current = current.plusSeconds(1)) {
if (isWinner(current)) {
count++;
}
}
That's it.
The question is really more geared towards getting a feel of how you'd approach the problem, and if you know about LocalTime API etc.
I'm a novice Java student. I have only been studying programming for a few months at school, and so I am currently pretty bad at it, and often feel stuck doing my assignments.
Anyway, I have a question regarding an assignment. I have been looking around and not quite finding the answers I need, so I was hoping to find some help on here. It would be much appreciated. My assignment goes like this: "Write a program that creates a Date object and a Random object. Use the Random object to set the elapsed time of the Date object in a loop to 10 long values between 0 and 100000000000 and display the random longs and the corresponding date and time."
We were just introduced to the classes java.util.Random and java.util.Date to work with this assignment, and are expected to use them to create the needed Date and Random objects.
The only things I really know how to do for this assignment are how to start the code:
public class RanDate {
public static void main(String[] args) {
And how to create the loop:
for (int i = 0; i <= 10; i++) {
I'm sorry if my question was too vague, or if I didn't ask something properly. This is my first time asking for help on this site. Thank you in advance for your help.
How about this?
Random rnd = new Random();
Date date = new Date(Math.abs(System.currentTimeMillis() - rnd.nextLong()));
System.out.println(date.toString());
Just subtract the actual time System.currentTimeMillis() and random generated long number with rnd.nextLong(). It's better finally wrap it all to Math.abs().
Try this code.
I think the assignment asks for the long to be the value in the date object, but I'm not shure.
public static void main(String[] args) {
Long max =0L;
Long min =100000000000L;
//Use the date format that best suites you
SimpleDateFormat spf = new SimpleDateFormat("dd/MM/yyyy");
for (int i = 0; i <= 10; i++) {
Random r = new Random();
Long randomLong=(r.nextLong() % (max - min)) + min;
Date dt =new Date(randomLong);
System.out.println("Generated Long:"+ randomLong);
System.out.println("Date generated from long: "+spf.format(dt));
}
}
Sample Output:
Generated Long:68625461379
Date generated from long: 05/03/1972
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
What are some intuition behind how much time it takes for my piece of code to run? (i.e. how much time does it take to add 100 objects into an ArrayList in java?)
To clarify, I'm not looking for timers. I'm looking for low-level discussions on how long each instruction takes. For example, assuming we have the following set-up
Object[] array = new Object[100];
currentIndex = 0;
// I call myList.add(myObject);
How long does each instruction take:
Instruction 1:
the first Object pointer in the array will reference myObject?
Instruction 2:
currentIndex++
Instruction 3:
if(currentIndex>100)
// resize internal array
class TimeTest1 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
}
}
try this
There's absolutely no "intuition" whatsoever. You have to measure.
And benchmark.
And profile.
And test.
In modern computing environments, there are just so many (bigger and smaller) details that the actual execution speed of a particular operation depends on, that it's practically impossible to tell "intuitively" how long it will take to execute it.
If you have data about the computational complexity of your algorithm, you may be able to come up with approximations with regards to the change in (ratio of) execution times as a function of the change in (ratio of) the input sizes. But that's a completely different beast.
This will work:
long startTime = System.nanoTime();
//do something - add 100 objects in ArrayList
long endTime = System.nanoTime();
System.out.println(endTime - startTime);
This question already has answers here:
How do I time a method's execution in Java?
(42 answers)
Closed 9 years ago.
How do I calculate the time taken for the execution of a method in Java?
To be more precise, I would use nanoTime() method rather than currentTimeMillis():
long startTime = System.nanoTime();
myCall();
long stopTime = System.nanoTime();
System.out.println(stopTime - startTime);
In Java 8 (output format is ISO-8601):
Instant start = Instant.now();
Thread.sleep(63553);
Instant end = Instant.now();
System.out.println(Duration.between(start, end)); // prints PT1M3.553S
Guava Stopwatch:
Stopwatch stopwatch = Stopwatch.createStarted();
myCall();
stopwatch.stop(); // optional
System.out.println("Time elapsed: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS));
You can take timestamp snapshots before and after, then repeat the experiments several times to average to results. There are also profilers that can do this for you.
From "Java Platform Performance: Strategies and Tactics" book:
With System.currentTimeMillis()
class TimeTest1 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
}
}
With a StopWatch class
You can use this StopWatch class, and call start() and stop before and after the method.
class TimeTest2 {
public static void main(String[] args) {
Stopwatch timer = new Stopwatch().start();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
timer.stop();
System.out.println(timer.getElapsedTime());
}
}
See here (archived).
NetBeans Profiler:
Application Performance Application
Performance profiles method-level CPU
performance (execution time). You can
choose to profile the entire
application or a part of the
application.
See here.
Check this: System.currentTimeMillis.
With this you can calculate the time of your method by doing:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;
In case you develop applications for Android you should try out the TimingLogger class.
Take a look at these articles describing the usage of the TimingLogger helper class:
Measuring performance in the Android SDK (27.09.2010)
Discovering the Android API - Part 1 (03.01.2017)
You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.
If you use Spring, take a look at their MethodInterceptor class.
If you are currently writing the application, than the answer is to use System.currentTimeMillis or System.nanoTime serve the purpose as pointed by people above.
But if you have already written the code, and you don't want to change it its better to use Spring's method interceptors. So for instance your service is :
public class MyService {
public void doSomething() {
for (int i = 1; i < 10000; i++) {
System.out.println("i=" + i);
}
}
}
To avoid changing the service, you can write your own method interceptor:
public class ServiceMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = methodInvocation.proceed();
long duration = System.currentTimeMillis() - startTime;
Method method = methodInvocation.getMethod();
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
System.out.println("Method '" + methodName + "' took " + duration + " milliseconds to run");
return null;
}
}
Also there are open source APIs available for Java, e.g. BTrace.
or Netbeans profiler as suggested above by #bakkal and #Saikikos.
Thanks.
As proposed nanoTime () is very precise on short time scales.
When this precision is required you need to take care about what you really measure.
Especially not to measure the nanotime call itself
long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization
long start2 = System.nanoTime();
myCall();
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;
System.out.println(diff + " ns");
By the way, you will measure different values for the same call due to
other load on your computer (background, network, mouse movement, interrupts, task switching, threads)
cache fillings (cold, warm)
jit compiling (no optimization, performance hit due to running the compiler, performance boost due to compiler (but sometimes code with jit is slower than without!))
Nanotime is in fact not even good for elapsed time because it drifts away signficantly more than currentTimeMillis. Furthermore nanotime tends to provide excessive precision at the expense of accuracy. It is therefore highly inconsistent,and needs refinement.
For any time measuring process,currentTimeMillis (though almost as bad), does better in terms of balancing accuracy and precision.