如何测量java程序中方法的cpu使用情况

时间:2015-10-28 08:44:46

标签: java performance profiling

我想测量Java应用程序中的CPU使用率,例如

string sql = ";WITH getUniqueParams AS (" +
                               "SELECT DISTINCT [a] AS 'param' FROM [table]" +  
                               "UNION ALL " + 
                               "SELECT DISTINCT [b] AS 'param' FROM [table]" + 
                               "UNION ALL " + 
                               "SELECT DISTINCT [c] AS 'param' FROM [table]" +  
                               "UNION ALL " + 
                               "SELECT DISTINCT [d] AS 'param' FROM [table]" + 
                               "UNION ALL " + 
                               "SELECT DISTINCT [e] AS 'param' FROM [table]" +  
                               "UNION ALL " + 
                               "SELECT DISTINCT [f] AS 'param' FROM [table]" +  
                               "UNION ALL " + 
                               "SELECT DISTINCT [g] AS 'param' FROM [table]" + 
                               "UNION ALL " + 
                               "SELECT DISTINCT [h] AS 'param' FROM [table]" +  
                               "UNION ALL " + 
                               "SELECT DISTINCT [i] AS 'param' FROM [table]" +  
                               "UNION ALL " + 
                               "SELECT DISTINCT [j] AS 'param' FROM [table]" +
                               "UNION ALL " + 
                               "SELECT DISTINCT [k] AS 'param' FROM [table]) " + 
                               "SELECT DISTINCT [param] FROM getUniqueParams ORDER BY [param]";   //the result of this statement to be stored in a string

            List<string> lUniqueParams = new List<string>();

            // set up SQL connection and command
            using (SqlConnection conn = new SqlConnection(@"Data Source=server;Initial Catalog=db;Integrated Security=SSPI"))
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                conn.Open();

                // get a SqlDataReader to read multiple rows
                using (SqlDataReader rdr = cmd.ExecuteReader()) //getting exception here when debugging
                {
                    // while there are more result rows.....
                    while (rdr.Read())
                    {
                        // grab the 0-index value from the result row
                        lUniqueParams.Add(rdr.GetString(0));
                    }
                }

                conn.Close();
                conn.Dispose();
            }
HelloWorld应用程序的

。任何的想法?我不想测量整个应用程序的CPU使用率,只测量应用程序中的方法。

有没有办法将应用程序的总执行时间与整个应用程序的CPU使用率相关联?

1 个答案:

答案 0 :(得分:1)

在我看来,分析单一方法没有意义。因为a)很容易发现资源占用方法(即如果你必须迭代10000个输入值才能找到你想要输出的100个有效值,那么很明显你没有效率并浪费了9900的CPU时间无用的迭代)和b)高效设计的关键是预见资源的浪费,并再次使用与a点相同的例子,由设计师找到更有效的方法来解决问题,使用更精简和更快的数据结构或只是找到一种方法来修剪方法中的垃圾数据。

编辑:不,由于Java JIT以及它自动使用垃圾收集器这一事实,无法将执行时间和CPU使用率关联起来。