How To Use TKPROF To Trace And Analyze Sql Explan

The SQL Trace facility and TKPROF let you accurately assess the efficiency of the SQL statements an application runs. For best results, use these tools withEXPLAIN PLAN rather than using EXPLAIN PLAN alone.

Using the SQL Trace Facility and TKPROF:

1、设置TIMED_STATISTICS为True,可以在会话级别,也可以在实例级别。

会话级:

SQL> alter session set timed_statistics=True;

实例级:

SQL> alter system set timed_statistics=True scope=both;

2、 设置SQL_TRACE,可以在会话级,也可以在数据库级。

会话级:

SQL> alter session set sql_trace=true;

或者:

SQL>EXEC DBMS_SYSTEM.SET_SQL_TRACE_IN_SESSION(SID,SERIAL#,TRUE);

实例级:

SQL> alter system set sql_trace=true scope=both;

For Example:

[email protected]>show parameter sql_trace;
NAME                                 TYPE                   VALUE
———————————— ———————- ——————————
sql_trace                            boolean                TRUE
[email protected]>show parameter timed;
NAME                                 TYPE                   VALUE
———————————— ———————- ——————————
timed_os_statistics                  integer                0
timed_statistics                     boolean                TRUE
select * from dba_objects where rownum<2000;

how to get trace file?

[email protected]>select username,sid,serial# from v$session where username='SYS';
USERNAME               SID    SERIAL#
————— ———- ———-
SYS                      1         13

[email protected]>select 'orcl_ora_'||spid||'.trc' from v$process where addr = (select paddr from v$session where sid=1);
'ORCL_ORA_'||SPID||'.TRC'
————————————————————————–
orcl_ora_1996.trc
or:
create or replace function gettracename  return varchar2 is
  v_result varchar2(200);
begin
  SELECT    d.VALUE
      || '/'
      || LOWER (RTRIM (i.INSTANCE, CHR (0)))
      || '_ora_'
      || p.spid
      || '.trc' into v_result
  FROM (SELECT p.spid
          FROM v$mystat m, v$session s, v$process p
        WHERE m.statistic# = 1 AND s.SID = m.SID AND p.addr = s.paddr) p,
      (SELECT t.INSTANCE
          FROM v$thread t, v$parameter v
        WHERE v.NAME = 'thread'
          AND (v.VALUE = 0 OR t.thread# = TO_NUMBER (v.VALUE))) i,
      (SELECT VALUE
          FROM v$parameter
        WHERE NAME = 'user_dump_dest') d;
  return v_result;
end gettracename;
运行SQL> select gettracename() from dual;即可
SQL> select gettracename() from dual;

Or:

[email protected]>show parameter user_dump;
NAME                                 TYPE                   VALUE
———————————— ———————- ——————————
user_dump_dest                       string                 /opt/oracle/diag/rdbms/orcl11g
/orcl11g/trace

cd /opt/oracle/diag/rdbms/orcl11g/orcl11g/trace

ls -lrt

Start tkprof:

tkprof orcl11g_ora_1996.trc /opt/orcl11g_ora_1996.txt aggregate=yes sys=no waits=yes sort=fchela
more /opt/orcl11g_ora_1996.txt
TKPROF: Release 11.2.0.4.0 – Development on Sat Aug 23 10:34:50 2014
Copyright (c) 1982, 2011, Oracle and/or its affiliates.  All rights reserved.

Trace file: orcl11g_ora_1996.trc
Sort options: fchela
********************************************************************************
count    = number of times OCI procedure was executed
cpu      = cpu time in seconds executing
elapsed  = elapsed time in seconds executing
disk     = number of physical reads of buffers from disk
query    = number of buffers gotten for consistent read
current  = number of buffers gotten in current mode (usually for update)
rows     = number of rows processed by the fetch or execute call
********************************************************************************

The following statement encountered a error during parse:

create test as selec …
PARSE #140386925570984:c=0,e=
Error encountered: ORA-00901
********************************************************************************

SQL ID: bcg7084jc4um6 Plan Hash: 1388734953

select sdo_geor_def.getSqlText
from
dual

call     count       cpu    elapsed       disk      query    current        rows
——- ——  ——– ———- ———- ———- ———-  ———-
Parse        1      0.01       0.01          0         18          0           0
Execute      1      0.00       0.00          0          0          0           0
Fetch        1      0.02       0.02          0         36          0           1
——- ——  ——– ———- ———- ———- ———-  ———-
–More–(6%)

21.4.3.2 Syntax of TKPROF

TKPROF is run from the operating system prompt. The syntax is:

tkprof filename1 filename2 [waits=yes|no] [sort=option] [print=n]

[aggregate=yes|no] [insert=filename3] [sys=yes|no] [table=schema.table]

[explain=user/password] [record=filename4] [width=n]

The input and output files are the only required arguments. If you invoke TKPROF without arguments, then the tool displays online help. Use the arguments inTable 21-2 with TKPROF.

Table 21-2 TKPROF Arguments


Argument


Description


filename1


Specifies the input file, a trace file containing statistics produced by the SQL Trace facility. This file can be either a trace file produced for a single session, or a file produced
by concatenating individual trace files from multiple sessions.


filename2


Specifies the file to which TKPROF writes its formatted output.


WAITS


Specifies whether to record summary for any wait events found in the trace file. Values are YES or NO. The default isYES.


SORT


Sorts traced SQL statements in descending order of specified sort option before listing them into the output file. If multiple options are specified, then the output is sorted
in descending order by the sum of the values specified in the sort options. If you omit this parameter, then TKPROF lists statements into the output file in order of first use. Sort options are listed as follows:


PRSCNT


Number of times parsed.


PRSCPU


CPU time spent parsing.


PRSELA


Elapsed time spent parsing.


PRSDSK


Number of physical reads from disk during parse.


PRSQRY


Number of consistent mode block reads during parse.


PRSCU


Number of current mode block reads during parse.


PRSMIS


Number of library cache misses during parse.


EXECNT


Number of executes.


EXECPU


CPU time spent executing.


EXEELA


Elapsed time spent executing.


EXEDSK


Number of physical reads from disk during execute.


EXEQRY


Number of consistent mode block reads during execute.


EXECU


Number of current mode block reads during execute.


EXEROW


Number of rows processed during execute.


EXEMIS


Number of library cache misses during execute.


FCHCNT


Number of fetches.


FCHCPU


CPU time spent fetching.


FCHELA


Elapsed time spent fetching.


FCHDSK


Number of physical reads from disk during fetch.


FCHQRY


Number of consistent mode block reads during fetch.


FCHCU


Number of current mode block reads during fetch.


FCHROW


Number of rows fetched.


USERID


Userid of user that parsed the cursor.


PRINT


Lists only the first integer sorted SQL statements from the output file. If you omit this parameter, then TKPROF lists all traced SQL statements. This parameter does not affect
the optional SQL script. The SQL script always generates insert data for all traced SQL statements.


AGGREGATE


If you specify AGGREGATE = NO, then TKPROF does not aggregate multiple users of the same SQL text.


INSERT


Creates a SQL script that stores the trace file statistics in the database. TKPROF creates this script with the namefilename3. This script creates a table and inserts a row of
statistics for each traced SQL statement into the table.


SYS


Enables and disables the listing of SQL statements issued by the user SYS, or recursive SQL statements, into the output file. The default value of YES causes TKPROF to list these
statements. The value of NO causes TKPROF to omit them. This parameter does not affect the optional SQL script. The SQL script always inserts statistics for all traced SQL statements, including recursive SQL statements.


TABLE


Specifies the schema and name of the table into which TKPROF temporarily places execution plans before writing them to the output file. If the specified table exists, then TKPROF deletes
all rows in the table, uses it for the EXPLAIN PLANstatement (which writes more rows into the table), and then deletes those rows. If this table does not exist, then TKPROFcreates it, uses it, and then drops it.

The specified user must be able to issue INSERT, SELECT, and DELETE statements against the table. If the table does not exist, then the user must also be able to issue CREATE TABLE and DROP TABLE statements.
For the privileges to issue these statements, see the Oracle Database SQL Language Reference.

This option allows multiple individuals to run TKPROF concurrently with the same user in the EXPLAIN value. These individuals can specify different TABLE values and avoid destructively
interfering with each other‘s processing on the temporary plan table.

If you use the EXPLAIN parameter without the TABLE parameter, then TKPROF uses the table PROF$PLAN_TABLE in the schema of the user specified by the EXPLAIN parameter. If you use
the TABLE parameter without the EXPLAIN parameter, then TKPROF ignores the TABLE parameter.

If no plan table exists, TKPROF creates the table PROF$PLAN_TABLE and then drops it at the end.


EXPLAIN


Determines the execution plan for each SQL statement in the trace file and writes these execution plans to the output file. TKPROF determines
execution plans by issuing the EXPLAIN PLAN statement after connecting to Oracle Database with the user and password specified in this parameter. The specified user must have CREATE SESSION system privileges.TKPROF takes
longer to process a large trace file if the EXPLAIN option is used.


RECORD


Creates a SQL script with the specified filename4 with all of the nonrecursive SQL in the trace file. You can use this script to replay the user events from the trace file.


WIDTH


An integer that controls the output line width of some TKPROF output, such as the explain plan. This parameter is useful for post-processing of TKPROF output.

21.4.3.3 Examples of TKPROF Statement

This section provides two brief examples of TKPROF usage. For an complete example of TKPROF output, see "Sample TKPROF Output".

21.4.3.3.1 TKPROF Example 1

If you are processing a large trace file using a combination of SORT parameters and the PRINT parameter, then you can produce a TKPROF output file containing only the highest resource-intensive
statements. For example, the following statement prints the 10 statements in the trace file that have generated the most physical I/O:

TKPROF ora53269.trc ora53269.prf SORT = (PRSDSK, EXEDSK, FCHDSK) PRINT = 10
21.4.3.3.2 TKPROF Example 2

This example runs TKPROF, accepts a trace file named examp12_jane_fg_sqlplus_007.trc, and writes a formatted output file named outputa.prf:

TKPROF examp12_jane_fg_sqlplus_007.trc OUTPUTA.PRF
EXPLAIN=scott/tiger TABLE=scott.temp_plan_table_a INSERT=STOREA.SQL SYS=NO
SORT=(EXECPU,FCHCPU)

This example is likely to be longer than a single line on the screen, and you might need to use continuation characters, depending on the operating system.

Note the other parameters in this example:

  • The EXPLAIN value causes TKPROF to connect as the user scott and use the EXPLAIN PLAN statement to generate the execution plan for each traced SQL statement. You can use this to
    get access paths and row source counts.

    Note:

    If the cursor for a SQL statement is not closed, then TKPROF output does not automatically include the actual execution plan of the SQL statement. In this situation, you can use
    the EXPLAIN option with TKPROF to generate an execution plan.

  • The TABLE value causes TKPROF to use the table temp_plan_table_a in the schema scott as a temporary plan table.
  • The INSERT value causes TKPROF to generate a SQL script named STOREA.SQL that stores statistics for all traced SQL statements in the database.
  • The SYS parameter with the value of NO causes TKPROF to omit recursive SQL statements from the output file. In this way, you can ignore internal Oracle Database statements such
    as temporary table operations.
  • The SORT value causes TKPROF to sort the SQL statements in order of the sum of the CPU time spent executing and the CPU time spent fetching rows before writing them to the output
    file. For greatest efficiency, always use SORT parameters.

21.4.4 Step 4: Interpreting TKPROF Output

This section provides pointers for interpreting TKPROF output.

  • Tabular Statistics in TKPROF
  • Row Source Operations
  • Wait Event Information
  • Interpreting the Resolution of Statistics
  • Understanding Recursive Calls
  • Library Cache Misses in TKPROF
  • Statement Truncation in SQL Trace
  • Identification of User Issuing the SQL Statement in TKPROF
  • Execution Plan in TKPROF
  • Deciding Which Statements to Tune

While TKPROF provides a very useful analysis, the most accurate measure of efficiency is the actual performance of the application in question. At the end of theTKPROF output is
a summary of the work done in the database engine by the process during the period that the trace was running.

21.4.4.1 Tabular Statistics in TKPROF

TKPROF lists the statistics for a SQL statement returned by the SQL Trace facility in rows and columns. Each row corresponds to one of three steps of SQL statement processing.
Statistics are identified by the value of the CALL column. See Table 21-3.

Table 21-3 CALL Column Values


CALL Value


Meaning


PARSE


Translates the SQL statement into an execution plan, including checks for proper security authorization and checks for the existence of tables, columns, and other referenced objects.


EXECUTE


Actual execution of the statement by Oracle. For INSERT, UPDATE, and DELETE statements, this modifies the data. ForSELECT statements, this identifies the selected rows.


FETCH


Retrieves rows returned by a query. Fetches are only performed for SELECT statements.

The other columns of the SQL Trace facility output are combined statistics for all parses, all executes, and all fetches of a
statement. The sum of query andcurrent is the total number of buffers accessed, also called Logical I/Os (LIOs). See Table 21-4.

Table 21-4 SQL Trace Statistics for Parses, Executes, and Fetches.


SQL Trace Statistic


Meaning


COUNT


Number of times a statement was parsed, executed, or fetched.


CPU


Total CPU time in seconds for all parse, execute, or fetch calls for the statement. This value is zero (0) ifTIMED_STATISTICS is not turned on.


ELAPSED


Total elapsed time in seconds for all parse, execute, or fetch calls for the statement. This value is zero (0) ifTIMED_STATISTICS is not turned on.


DISK


Total number of data blocks physically read from the data files on disk for all parse, execute, or fetch calls.


QUERY


Total number of buffers retrieved in consistent mode for all parse, execute, or fetch calls. Usually, buffers are retrieved in consistent
mode for queries.


CURRENT


Total number of buffers retrieved in current mode. Buffers are retrieved in current mode for statements such asINSERT, UPDATE,
and DELETE.

Statistics about the processed rows appear in the ROWS column. See Table 21-5.

Table 21-5 SQL Trace Statistics for the ROWS Column


SQL Trace Statistic


Meaning


ROWS


Total number of rows processed by the SQL statement. This total does not include rows processed by subqueries of the SQL statement.

For SELECT statements, the number of rows returned appears for the fetch step. For UPDATE, DELETE, and INSERT statements, the number of rows processed appears for the execute step.

Note:

The row source counts are displayed when a cursor is closed. In SQL*Plus, there is only one user cursor, so each statement executed causes the previous cursor to be closed; therefore,
the row source counts are displayed. PL/SQL has its own cursor handling and does not close child cursors when the parent cursor is closed. Exiting (or reconnecting) causes the counts to be displayed.

时间: 2024-10-05 23:56:51

How To Use TKPROF To Trace And Analyze Sql Explan的相关文章

oracle中如何使用TKPROF命令查看Trace file

Trace file(追踪文件)是以trc为后续的文本文件,它记录了各种sql操作及所消耗的时间等,根据trace文件我们就可以了解哪些sql导致了系统的性能瓶颈,进而采取恰当的方式调优. 当我们操作oracle数据库,每次都会产生一个会话(session),session中记录了所有操作,这些操作都会记录在trace文件中. 如何使用TKPROF命令查看Trace file: SQL>alter session set sql_trace=true; SQL>select count(*)

转 怎样解读10046 trace (tkprof 的结果 )

TKProf Structure TKProf output for an individual cursor has the following structure: SELECT NULL FROM DUAL call     count       cpu    elapsed       disk      query    current        rows------- ------  -------- ---------- ---------- ---------- -----

使用 10046 查看执行计划并读懂 trace 文件

查看 sql 执行计划的方法有许多种, 10046 事件就是其中的一种. 与其他查看 sql 执行计划不同, 当我们遇到比较复杂的 sql 语句, 我们可以通过 10046 跟踪 sql 得到执行计划中每一个步骤的逻辑读, 物理读以及花费的时间等. 这种细粒度的跟踪对于我们分析 sql 性能尤其有用. 一般来说, 使用 10046 事件得到 sql 执行计划的步骤如下: 1. 激活当前 session 10046 事件 2. 在当前 session 中执行 sql 语句 3. 关闭当前 sess

10046 trace文件分析

SQL> create table t10046 as select * from dba_objects; Table created. SQL> select file_id,block_id,blocks from dba_extents where segment_name='T10046'; FILE_ID BLOCK_ID BLOCKS ---------- ---------- ---------- 1 94664 8 1 94672 8 1 94680 8 1 94688 8

Oracle 10046 trace文件分析

生成10046 trace文件: SQL> create table t10046 as select * from dba_objects; Table created. SQL> select file_id,block_id,blocks from dba_extents where segment_name='T10046'; FILE_ID BLOCK_ID BLOCKS ---------- ---------- ---------- 1 94664 8 1 94672 8 1 9

SQL_TRACE与tkprof分析

一. SQL_TRACE 当SQL语句出现性能问题时,我们可以用SQL_TRACE来跟踪SQL的执行情况,通过跟踪,我们可以了解一条SQL或者PL/SQL包的运行情况,SQL_TRACE命令会将SQL执行的整个过程输出到一个trace文件中,我们可以读这个trace 文件来了解在这个SQL执行过程中Oracle 都做了哪些操作. 可以通过sql命令启动SQL_TRACE,或者在初始化参数里面. SQL>alter session set sql_trace=true; 或者 SQL> alte

10046入门:使用 10046 查看执行计划并读懂 trace文件

************************************************************* 1.开启10046 ************************************************************* SQL> oradebug setmypid Statement processed. // 激活 10046 事件 SQL> oradebug event 10046 trace name context forever,lev

Oracle SQL Trace 和 10046 事件

一. SQL_TRACE 当SQL语句出现性能问题时,我们可以用SQL_TRACE来跟踪SQL的执行情况,通过跟踪,我们可以了解一条SQL或者PL/SQL包的运行情况,SQL_TRACE命令会将SQL执行的整个过程输出到一个trace文件中,我们可以读这个trace 文件来了解在这个SQL执行过程中Oracle 都做了哪些操作. 可以通过sql命令启动SQL_TRACE,或者在初始化参数里面. SQL>alter session set sql_trace=true; 或者 SQL> alte

Oracle性能分析3:TKPROF简介

tkprof它是Oracle它配备了一个命令直插式工具,其主要作用是将原始跟踪文件格文本文件的类型,例如,最简单的方法,使用下面的: tkprof ly_ora_128636.trc ly_ora_128636.txt tkprof带有非常多參数,在多数情况下,使用这些參数对你的分析将非常有帮助. tkprof參数 假设不带不论什么參数执行tkprof,它将打印出完整的參数列表,并带有简单的描写叙述.以下是对參数的说明: explain 为每一个SQL语句提供一个运行计划. 该參数须要指定用户.