0

I want to write a function, which prints the runtime of any other function which take as an argument along with parameters. Example my idea in python for a better understanding:


def runtimer(func , *args, **kwargs):
    start = time.time()
    result = func(*args, **kwargs)
    print(time.time() - start)
    return result


runtimer(time.sleep, 1)

Output: 1.000108242034912

I'm trying to use val: _* parameter, but it implements "all or nothing". In another way I checked print function in source scala github, but I did not find anything applicable to my question.

I would like to know if this is possible to solve on scala or get any advice. A java implementation will also be useful.

Thanks!

UPD: I will leave here some most useful references: the first for the most similar implementation, second maximum correct for runtime calculating on JVM (by comment): 1) How to profile methods in Scala? 2) Scala : function to measure the runtime of any other function

The question is still open, I'm waiting for discussions

  • 2
    @MarioGalic I believe the accepted answer of the duplicate is totally wrong, that is not the correct way to benchmark on the JVM. I believe it would better to link to [this answer](https://stackoverflow.com/questions/59598239/why-is-zipped-faster-than-zip-in-scala/59600699#59600699) – Luis Miguel Mejía Suárez Mar 05 '20 at 14:36
  • I’ll clarify that not high accuracy is important, that is, this fencing is necessary to calculate the operating time of algorithms that work for more than a minute and accuracy can be important at +-10%. Now I use this code: time = System.currentTimeMillis() func() println("Runtime: " + System.currentTimeMillis() - time) – Ilya Kotelnikov Mar 05 '20 at 15:32
  • If you want a Java profiling function, you should break that up into a separate question. It's entirely independent of the Scala profiling function. – Ethan Mar 05 '20 at 16:13
  • 1
    @LuisMiguelMejíaSuárez I've updated [How to profile methods in Scala?](https://stackoverflow.com/q/9160001/5205022) with hopefully correct [answer](https://stackoverflow.com/a/61035954/5205022) based on Travis'. – Mario Galic Apr 04 '20 at 23:36

1 Answers1

0

To solve your problem, you have to use HOFs (higher-order functions). Those are functions which take other functions as parameters. Here is an example of how it can be done for function with one parameter.

 def measure(yourFunction: (Int) => Int, arg1: Integer): Double = {
   val startTime = System.nanoTime()
   yourFunction(arg1)
   System.nanoTime() - startTime 
 }

As you can see, this function measures time for functions which take Int as a parameter and return Int. I've translated your Python code to Scala

NJ

  • Yes it's work, but I want to write a universal function, not only for 1 or only 2 parameters. Someone mark this answer with good reference for me (with call-by-name): https://stackoverflow.com/questions/9160001/how-to-profile-methods-in-scala – Ilya Kotelnikov Mar 06 '20 at 14:10