When data is not found in the cache, it is called a cache miss. A cache is only effective if it has a low miss rate. The miss ratio can be calculated by dividing the number of times a record gets read from the DB (it only gets read from the DB if it wasn’t found in the cache, indicating a cache miss), versus the number of times a record was looked for:
# Cache Misses
Hit Ratio = -------------- * 100
# Total Reads
The lower the miss ratio, the fewer the data items get read from the database and the more performance gain you are experiencing from using the caching logic. A high cache miss ratio can indicate that the cache size is too small, or that the data you are caching is not suitable for caching, i.e. there are too many distinct values that get queried resulting in high turnover (see later).
In order to be able to calculate the ratio, we just need to keep track of the number of db reads (on top of the total number of reads which we already keep track of).
g_total_db_hits PLS_INTEGER := 0;
And then we change our existing code to gather the numbers (if requested):
FUNCTION read_from_db (p_dept_id IN dept.deptno%TYPE) RETURN department_tp AS l_dept_data department_tp; CURSOR csr_dept_data (p_dept_id IN dept.deptno%TYPE) IS SELECT dname, loc FROM dept WHERE deptno = p_dept_id; BEGIN OPEN csr_dept_data (p_dept_id); FETCH csr_dept_data INTO l_dept_data;
IF (csr_dept_data%FOUND) THEN IF (gather_stats) THEN g_total_db_hits := g_total_db_hits + 1;
END IF; END IF;
CLOSE csr_dept_data; RETURN l_dept_data; END read_from_db;
Now we just need to create a procedure to actually perform the calculations of the ratio:
FUNCTION db_hit_ratio RETURN NUMBER AS l_db_hit_ratio NUMBER (10, 5); BEGIN IF (g_total_reads <> 0) THEN l_db_hit_ratio := (g_total_db_hits / g_total_reads) * 100; END IF;