Welcome, guest | Sign In | My Account | Store | Cart
1

Use Jython to time java code. An inexpensive solution to measure Java code's performance. In the following example, jtimeit.py is created to measure Main.doHttpGet()'s performance. Used google and yahoo as examples.

Python, 81 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
jtimeit.py
===========
from java.lang import System
from java.net import URL
from java.io import *
import Main


def jtimeit(f,args):
    start=System.currentTimeMillis()
    f(*args)
    end=System.currentTimeMillis()
    
    return end-start


def sum(seq):
    # no sum in Jython 2.1, we will use reduce
    return reduce(lambda x,y:x+y,seq)
    
def avg(seq):
    return sum(seq)/len(seq)

def main():


    url1='http://www.google.com'
    url2='http://www.yahoo.com'

    # single hits
    print url1, ' takes ',jtimeit(Main.doHttpGet,[url1]),' ms\n'
    print url2, ' takes ',jtimeit(Main.doHttpGet,[url2]),' ms\n'

    # average over 10 hits
    g=[]
    y=[]
    for i in range(10):
      g.append(jtimeit(Main.doHttpGet,[url1]))
      y.append(jtimeit(Main.doHttpGet,[url2]))
    print url1, ' on average takes ', avg(g),' ms';
    print url2, ' on average takes ', avg(y),' ms';
    

if __name__=='__main__':
    main()



Main.java
==========
import java.net.*;
import java.io.*;


public class Main {

   
    public static void doHttpGet(String url) throws Exception {



	HttpURLConnection conn=(HttpURLConnection)(new URL(url)).openConnection();
	conn.setRequestMethod("GET");
	conn.connect();

	
	
      
	String inputLine;
    	    
	BufferedReader    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	    	
	while ((inputLine = reader.readLine()) != null) {
	    //  System.out.println(inputLine);
	}
	
	reader.close();
	conn.disconnect();


    }

Without any change in Java code such as Main.java, a jython script can be created to calculate the average time for the Java method. The key part is to use jtimeit(f,args). f can be a Jython module level function or Java static function.

Add a comment

Sign in to comment

Created by Victor Yang on Fri, 14 Jan 2005 (PSF)
Python recipes (4552)
Victor Yang's recipes (8)

Required Modules

  • (none specified)

Other Information and Tasks