2

I have a func a(x, y z) that would like to time, is there a way to this:

time = timeit( a(x,y,z) ) in java, time it would accept any func.

like:

long timeit(Object func){
    long startTime = System.currentTimeMillis();
    func(...);
    return System.currentTimeMillis() - startTime;
}
1
  • 6
    Either through reflection or Command pattern. Or use a scheduler. Commented Aug 8, 2013 at 14:42

3 Answers 3

5

You need place your function in Runnable interface, in public void run() method. Modified code:

public long timeit(Runnable func)
{
    long startTime = System.currentTimeMillis();
    func.run();
    return System.currentTimeMillis() - startTime;
}

Function:

public class MyFunction implements Runnable
{
    @Override public void run() { System.out.println(); }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I see, this would only work for functions implemented in this way.
Yes. Because Java can't pass function as argument like in JavaScript.
@AndreyRedov You can pass a Method object and call it via reflection
Yes, but the Runnable is better as it quicker and simpler.
1

Using Reflection:

If functionCall() is an instance method
-> create an object for the class
-> Invoke method using object of that class

MyClass objToPass = new MyClass();
Method m;
//Assuming functionCall() takes no arguments
m = MyClass.class.getMethod("functionCall", new Class[]{});
//Parameter list empty
m.invoke(objToPass, new Object[]{});

Comments

0

How about defining an interface (let's say FunctionRunner) with just one method (let's call it run()). Now you can implement this interface and do whatever you want to do when run() is being called. Then your Code to measure the time of a function would be like this:

long timeit(FunctionRunner func){
    long startTime = System.currentTimeMillis();
    func.run();
    return System.currentTimeMillis() - startTime;
}

2 Comments

Than this post differs from mine?
@Andrey: Not much, but I was faster :b ... but your solution is actually nicer, because you use Runnable, which is an existing interface

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.