viernes, 27 de mayo de 2016

Statspack

¿Qué es Statspack?


Es una herramienta que contiene Oracle, querecopila información de las vistas más importantes del

rendimiento. Este además analiza dichas estadísticas y genera un reporte con el diagnóstico global

de rendimiento. Además muestra la información recopilada en un formato legible para el

administrador de la Base de Datos.
¿Como es el reporte que genera?


El reporte que genera cuenta con una estructura definida:

En primer lugar nos muestra el diagnóstico en sí, en el cual se encuentran los indicadores de

desempeño (medición de las principales variables), y a continuación, los eventos que inciden en el

rendimiento.

En segundo lugar el reporte nos presenta todos los eventos de la base de datos.

Luego las sentencias SQL más consumidoras de recursos ordenadas de 4 formas:

-SQL ordenadas por llamadas.

-SQL ordenadas por lecturas.

-SQL ordenadas por ejecuciones.

-SQL ordenadas por llamadas analizadas.

A continuación, un listado de todas las estadísticas de la base de datos.

Continua con un listado de las tablespaces y los datafiles ordenados por la suma de lecturas y

escrituras.

Las siguientes estadísticas son las de uso de :

-Buffer pool

-PGA

-Undo Segments

-Latches

-Shared pool

Por último nos enseña parámetros del init.ora
ANÁLISIS DEL RENDIMIENTO DE ORACLE – ALEJANDRO CAMPOS 5

¿Cómo se instala?


Antes de instalar Statspack, es recomendable la creación de un tablespace de un mínimo de 500M,

ya que al instalarlo nos pedirá un tablespace que designar para la utilización de Statspack.

Para instalar Statspack, tan solo tendremos que ejecutar en sql plus, con cualquier usuario que

funcione como sysdba, el siguiente script:

@?/rdbms/admin/spcreate.sql

Este script creará también el usuario perfstat.

En la instalación se nos pedirá que elijamos el password del usuario perfstat, así como el tablespace

por defecto, y el tablespace temporal.
¿Cómo se recopilan las estadísticas?


Para tomar una foto en un momento determinado se debe de ejecutar el siguiente comando como

usuario perfstat en sql plus:

exec statspack.snap;

Sin embargo es recomendable automatizar la ejecución anterior, de forma que se fija la ejecución

del statspack cada hora exacta (7:00,8:00,9:00,....). Para ello se debe ejecutar el siguiente script:

@?/rdbms/admin/spauto.sql
¿Cómo se genera un reporte?


Para generar un reporte hay que ejecutar el siguiente script como usuario perfstat:

@?/rdbms/admin/spreport.sql

Se pedirá que indiques la instantánea inicial y la final de la que quieres hacer el reporte. También la

ubicación del fichero.
ANÁLISIS DEL RENDIMIENTO DE ORACLE – ALEJANDRO CAMPOS 6

Scripts Statspack

Instalación (como usuario sysdba):

-spcreate.sql: Instala Statspack ejecutando a su vez los scripts:

spcusr.sql: Crea el usuario PERFSTAT

spctab.sql: Crea las tablas

spcpkg.sql: Crea el paquete statspack

-spdrop.sql: Desinstala STATSPACK ejecutando a su vez los scripts:

spdtab.sql: Borra las tablas

spdusr.sql: Borra el usuario PERFSTAT
Informes (como usuario perfstat):

-spreport.sql: Genera un informe general del rendimiento de la instancia

-sprepins.sql: Genera un informe para la BD y la instancia indicados

-sprepsql.sql: Genera un informe para la sentencia SQL que se indique.

-spauto.sql: Permite automatizar la recolección de estadísticas.
Mantenimiento (como usuario perfstat):

sppurge.sql -> Permite borrar un rango de snapshots

sptrunc.sql -> Vacía todas las tablas, borrando todos los snapshots

spuexp.par -> Es un fichero de parámetros para exportar el usuario perfstat

jueves, 26 de mayo de 2016

Oracle Performance Tuning v$session_wait, v$sysstat

Oracle Performance Tuning

    Statistic Descriptions

    Various statistic definitions for columns found in the V$SESSION_WAIT and V$SYSSTAT dynamic performance tables.
    buffer busy waits This statistic is stored in V$SESSION_WAIT. In single-instance mode, concurrent I/O on a database block causes this statistic to increment. High buffer busy waits usually indicates a predominately I/O bound application.
    In an Oracle Parallel Server, it is common to wait for the buffer as the Distributed File System (DFS) lock gets escalated to Exclusive Mode. High buffer busy waits in an Oracle Parallel Server usually indicates competition between nodes for database blocks.
    P1 in the V$SESSION_WAIT table for this statistic is the database file number. P2 is the database block offset into that file. P3 uniquely identifies where in the RDBMS the event was triggered.
    consistent changes
    This statistic is stored in V$SYSSTAT. This statistic indicates the number of times a database block has rollback entries applied to perform a consistent read on the block.
    Workloads that produce a great deal of consistent changes can consume a great deal of resources.
    consistent gets This statistic is stored in V$SYSSTAT. This statistic indicates the number of times a consistent read was requested for a block. See also "consistent changes".
    db block changes This statistic is stored in V$SYSSTAT. Closely related to Consistent changes, this statistics counts the total number of changes that were made to all blocks in the SGA that were part of an update or delete operation. These are changes that are generating redo log entries and hence will be permanent changes to the database if the transaction is committed.
    This statistic is a rough indication of total database work. This statistic indicates (possibly on a per transaction level) the rate at which buffers are being dirtied.
    db block gets This statistic is stored in V$SYSSTAT. This statistic tracks the number of blocks gotten in current mode.
    free buffer waits This statistic is stored in V$SYSSTAT. This statistic stores the number of times a free buffer was requested in the SGA, but none were available. Free buffers are buffers that are not currently being used by other database users.
    If the SGA is full of dirty buffers and DBWR can't write them to disk, them then free buffer waits will increase. Update-intensive applications that use small indexes or hash clusters may run the risk of having an entire SGA full of dirty buffers that DBWR cannot keep up with.
    parse count This statistic is stored in V$SYSSTAT. Independant of any cache benefits that may occur in the library cache, this statistic counts the number of times the user called 'parse' function from either OCI or the Oracle Precompilers.
    This statistic is used mostly as a denominator in conjunction with the V$LIBRARY_CACHE table to determine actual hit ratios in the shared SQL area.
    physical reads This statistic is stored in V$SYSSTAT. This statistic stores the number of I/O requests to the operating system to retrieve a database block from the disk subsystem. This is a buffer cache miss.
    Logical reads is consistent gets + database block gets. Logical reads and physical reads is used to calculate the buffer cache hit ratio.
    physical writes This statistic is stored in V$SYSSTAT. This statistic stores the number of I/O requests to the operating system to write a database block to the disk subsystem. The bulk of the writes are performed either by DBWR or LGWR.
    recursive calls This statistic is stored in V$SYSSTAT. Oracle maintains tables used for internal processing. When Oracle needs to make a change to these tables, it internally generates a SQL statement. These internal SQL statements generate recursive calls.
    redo entries This statistic is stored in V$SYSSTAT. This statistic increments each time redo entries are copied into the redo log buffer.
    redo log space requests This statistic is stored in V$SYSSTAT. The active log file has filed up and Oracle is waiting for disk space to be allocated for the redo log entries. Space is created by performing a log switch.
    Small Log files in relation to the size of the SGA or the commit rate of the workload can cause problems. When the log switch occurs, Oracle must ensure that all committed dirty buffers are written to disk before switching to a new log file. If you have a large SGA full of dirty buffers and small redo log files, a log switch must wait for DBWR to write dirty buffers to disk before continuing.
    Also examine the 'log file space/switch' wait event in V$SESSION_WAIT.
    redo sync writes This statistic is stored in V$SYSSTAT. Normally, redo that is generated and copied into the log buffer need not be flushed out to disk immediately. The log buffer is a circular buffer that LGWR periodically flushes. Redo sync writes increments when changes being applied must be written out to disk due to a commit.
    sorts (disk) This statistic is stored in V$SYSSTAT. If the number of disk writes is non-zero for a given sort operation, then this statistic is incremented.
    Sorts that require I/O to disk are quite resource intensive. Try increasing the initialization parameter SORT_AREA_SIZE.
    sorts (memory) This statistic is stored in V$SYSSTAT. If the number of disk writes is zero, then the sort was performed completely in memory and this statistic is incremented.
    This is more an indication of sorting activity in the application workload. You can't do much better than memory sorts, except maybe no sorts at all. Sorting is usually caused by selection criteria specifications within table join SQL operations.
    table fetch rowid This statistic is stored in V$SYSSTAT. When rows are fetched using a rowid (usually recovered from an index), each row returned increments this counter.
    This statistic is an indication of row fetch operations being performed with the aid of an index. Because doing table scans usually either indicates non-optimal queries or tables without indexes, this statistic should increase as the above issues have been addressed in the application.
    table fetch continued row This statistic is stored in V$SYSSTAT. When a row that spans more than one block is encountered during a fetch, this statistic is incremented.
    Retrieving rows that span more than one block increases the logical I/O by factor that corresponds to the number of blocks than need to be accessed. Exporting and re-Importing may eliminate this problem. Taking a closer look at the STORAGE parameters PCT_FREE and PCT_USED. This problem cannot be fixed if rows are larger than database blocks (for example, if the LONG datatype is used and the rows are extremely large).
    table scan blocks This statistic is stored in V$SYSSTAT. During scanning operations, each row is retrieved sequentially by Oracle and every each block encountered during the scan increments this statistic.
    Informs you the number of database blocks you had to get from the buffer cache for the purpose of scanning. Compare this to consistent gets to get a feeling for how much of the consistent read activity can be attributed to scanning.
    table scan rows This statistic is stored in V$SYSSTAT. This statistic is collected during a scan operation, but instead of counting the number of database blocks, it counts the rows being processed.
    table scans (long tables) This statistic is stored in V$SYSSTAT. Long (or conversely short) tables can be defined as tables that don't meet the short table criteria as described in "table scans (short)".

    table scans (short tables) This statistic is stored in V$SYSSTAT. Long (or conversely short) tables can be defined by optimizer hints coming down into the row source access layer of Oracle. The table must be below the initialization parameter SMALL_TABLE_THRESHOLD. In Parallel Server environments that support parallel query servers across instances, it can be determined if the cache partition will fit in the current SGA. If it does, then the table is considered small for scanning purposes.
    Users with a lot of small tables that qualify under the above conditions benefit greatly by having these tables cached in the SGA. For parallel query operations, the merge phase of the query will improve as the pieces to be merged have been cached.
    user calls This statistic is stored in V$SYSSTAT. Oracle allocates resources (Call State Ojbects) to keep track of relevant user call data structures every time you login, parse, or execute.
    When determining activity, the ratio of user calls to RPI calls, give you an indication of how much internal work gets generated as a result of the type of requests the user is sending to Oracle.
    user commits This statistic is stored in V$SYSSTAT. When a user commits a transaction, the redo generated that reflects the changes made to database blocks must be written to disk. Commits often represent the closest thing to a user transaction rate.
    user rollbacks This statistic is stored in V$SYSSTAT. This statistic stores the number of times users manually issue the ROLLBACK statement or an error occurs during users' transactions.
    write requests This statistic is stored in V$SYSSTAT. This statistic stores the number of time DBWR takes a batch of dirty buffers and writes them to disk.

miércoles, 25 de mayo de 2016

Gestion de Proyectos EVM – Gestión del valor ganado

Gestión del valor ganado paso a paso


EVM – Gestión del valor ganado

Es un método para medir el desempeño de un proyecto, permite comparar la cantidad de trabajo planificado con la cantidad de trabajo real que se ha realizado. Así se puede determinar si el trabajo va según lo previsto y dentro del presupuesto del proyecto.

EVM cubre las tres líneas base de la Gestión de Proyectos: Alcance, Costo y Tiempo. Unificándolo en un marco común que permite representar matemáticamente las relaciones entre ellas.

NOTA:

Hay toneladas de documentación sobre este método en internet, así que no voy a volver a decir lo mismo. En vez de eso, voy a intentar explicar todo esto por partes con un ejemplo paso a paso de este método.

Empecemos con los 4 variables principales del EVM con lo que se realizan todos los cálculos
BAC
Presupuesto a la conclusión (Budget At Completion).

La suma de todos los valores del presupuesto establecidos para el trabajo que se realizará en un proyecto.
El valor planificado total para el proyecto. También conocido como: Presupuesto a la Terminación; Presupuesto Final; o Presupuesto hasta la Terminación.
PV
Valor planeado (Planned Value). 

Indica el valor de tiempo que teníamos planificado en un momento dado del proyecto
EV
Valor Ganado ( Earned Value)

Representa el trabajo realizado en un momento dado. Representado en tiempo.
AC
Coste real (Actual Cost)

Indica el coste que llevamos a un momento dado para realizar el trabajo que llevamos realizado.

 
BAC
Cuanto se presupuesto en total del proyecto 
EAC
BAC/CPI        Cual es el costo final esperado
AC + BAC - EV
ETC
EAC- AC Cuanto dinero falta para completar el proyecto





Imaginemos que tenemos un proyecto con un presupuesto total de 200.000 € y un plazo para su realización de 12 meses. Inicialmente, según nuestra planificación de costes, los gastos no son lineales a lo largo de la vida del proyecto, si no que cada mes necesitamos una cierta cantidad de dinero:
Gasto Mensual
Acumulado
Mes 1
23.000,00
23.000,00
Mes 2
15.000,00
38.000,00
Mes 3
15.000,00
53.000,00
Mes 4
18.000,00
71.000,00
Mes 5
19.000,00
90.000,00
Mes 6
18.000,00
108.000,00
Mes 7
17.000,00
125.000,00
Mes 8
10.000,00
135.000,00
Mes 9
15.000,00
150.000,00
Mes 10
18.000,00
168.000,00
Mes 11
20.000,00
188.000,00
Mes 12
12.000,00
200.000,00
presupuesto
NOTA:
Lo más sencillo para el ejemplo, sería que el presupuesto fuera lineal, o sea, que cada mes gastáramos la misma cantidad de dinero. Pero esa premisa no suele ser lo habitual, ya que en cada periodo de tiempo, las tareas y los recursos dedicados pueden variar, por lo tanto los gastos son diferentes cada mes.
Ahora, al finalizar el quinto mes del proyecto, tenemos realizado un 30% del trabajo y un gasto acumulado de 58.000 € ¿Cómo vamos?
Empezamos calculando el EV a esa fecha:
  • Al final del quinto mes teníamos que tener realizado el 41,66% del trabajo: (5*100)/12.
  • El PV a esa fecha, es de 90.000 €
  • Por lo tanto, si solo llevamos realizado el 30% del trabajo en vez del 41,66%, para sacar el EV solo hay que aplicar una sencilla regla de tres:
EV = \frac{(90.000 * 30)}{41,66} = 64.800
Y nuestro coste real (AC) es de 58.000 €
Vale, esto esta muy bien ¿y ahora que? Ahora tenemos que calcular las variaciones que tenemos sobre el costo y el cronograma:
Variaciones:
CVCost Variance. Una medida de desempeño en función de los costos de un proyecto. También conocido como: Variación del Coste o Variación en los Costos.

Es la diferencia entre el Valor ganado y el Coste real.
CV = EV − AC
SVScheduled Variance. Una medida de desempeño del cronograma en un proyecto. También conocido como Variación de tiempo.

Es la diferencia entre el Valor ganado y el Valor planificado.
SV = EV − PV
Por lo tanto:
CV = 64.800 – 58.000 = 6.800
SV = 64.800 – 90.000 = -25.200
Ya, ya, pero ¿como vamos?
Pues está claro que si el coste del trabajo realizado menos el coste real es cero, eso quiere decir que vamos correctamente, así que:
CV = 0Correcto
CV > 0Hemos gastado menos de lo que presupuestamos
CV < 0Hemos gastado más de lo que teníamos presupuestado.
SV = 0Llevamos el cronograma a la perfección ¿Utopía?
SV > 0Hemos realizado más trabajo del planificado.
SV < 0Hemos realizado menos trabajo del planificado. Vamos retrasados.
Todo esto son valores absolutos y no nos dan una idea real de como va nuestro trabajo, para eso vamos a calcular los índices de desempeño.
índices de desempeño
CPICost Performance Index. Índice de desempeño del costo. Es la proporción del valor ganado y los costos reales.

CPI = EV / AC
SPISchedule Performance Index. Índice del desempeño del cronograma. Una medida de eficiencia del cronograma en un proyecto. Es la razón entre el valor ganado y valor planificado.

SPI = EV / PV
CPI = 64.800 / 58.000 = 1,117
SPI = 64.800 / 90.000 = 0,72
Si los índices son menores a 1, quiere decir que son desfavorables. En este caso, el SPI nos indica que solo hemos realizado el 72% de lo que estaba planificado en el cronograma.
Pero sin embargo, nuestro Índice de Desempeño de Costo (CPI) es mayor de 1. Vamos retrasado según el cronograma pero no hemos gastado lo que teníamos que haber gastado tras el quinto mes.
Cuando estamos ante esta situación y tenemos un índice favorable y otro desfavorable, podemos hacer uso de otro indicador, el CSI. Este indicador nos da una relación entre el costo y el cronograma y así saber que posibilidades tenemos de recuperar nuestro proyecto.
CSI = CPI * SPI
CSI = 1,117 * 0,72 = 0,80
La siguiente tabla define como interpretar el índice CSI.
CSI > 0,9Proyecto OK
CSI Entre 0,8 y 0,9Hay posibilidades de arreglarlo
CSI < 0.8Lo más probable es que no se arregle.
Por ahora, nuestro proyecto es salvable, así que aplicamos las medidas correctivas que estimemos oportunas para mejorar nuestro rendimiento y volvemos a revisar al final del sexto mes.
Vemos que hemos realizado el 45% del trabajo y llevamos un coste de 105.000 €, sabiendo que teníamos que tener realizado el 50% del trabajo, nos da los siguientes valores:
Indicadores
  • AC = 105.000
  • PV = 108.000
  • EV = 97.200
Variaciones
  • CV = -7.800
  • SV = -10.800
Índices
  • CPI = 0,92
  • SPI = 0,90
  • CSI = 0,83
Nuestro proyecto va mejorando, aunque todavía seguimos retrasados.
Al final del decimo mes, deberíamos llevar realizado el 83% del trabajo, sin embargo llevamos el 80% y un gasto de 175.000 €, con eso nos da lo siguiente:
Indicadores
  • AC = 175.000
  • PV = 168.000
  • EV = 161.280
Variaciones
  • CV = -13.720
  • SV = -7.720
Índices
  • CPI = 0,92
  • SPI = 0,96
  • CSI = 0,88
Bueno, bueno, vamos mejorando poco a poco, ahora hacemos el último esfuerzo y terminamos el mes doce con el 100% del trabajo realizado y un costo de 215.000 €, quedando así:
Indicadores
  • AC = 215.000
  • PV = 200.000
  • EV = 200.000
Variaciones
  • CV = -15.000
  • SV = 0
Índices
  • CPI = 0,93
  • SPI = 1
  • CSI = 0,93
Hemos terminado nuestro proyecto en plazo, pero con un sobre coste de 15.000 €. Como se ve, nuestro SPI es 1 y nuestro CPI es menor de 1, esto quiere decir que nuestro rendimiento en el cronograma al final a sido perfecto, sin embargo, a sido un poco desfavorable en cuanto al rendimiento del costo. Pero bueno, solo nos hemos excedido en un 7,5% del presupuesto, eso no esta nada mal ¿Verdad?
En el siguiente gráfico se puede ver la evolución de nuestro proyecto
progreso