Chapter 32: Exercises – Performance Tuning for COBOL Programs

These exercises progress through five tiers of cognitive complexity. Detailed solutions are provided for exercises 1–3, and hints are given for exercises 4–5. All remaining exercises include only the problem statement so you can practice independently.


Tier 1 — Recall

Exercise 1: Performance Metrics Identification

Problem: Match each performance metric with its definition.

Metric Definition
CPU Time ?
Elapsed Time ?
I/O Wait Time ?
EXCP Count ?
TCB Time ?
SRB Time ?

Choose from: (A) The number of physical I/O operations performed by a program. (B) Total wall-clock time from job start to job end, including waits. (C) Time spent by the processor executing the program's instructions. (D) Time the program spends waiting for I/O operations to complete. (E) CPU time consumed under the program's Task Control Block. (F) CPU time consumed under a Service Request Block for system services.

Solution | Metric | Definition | |----------------|------------| | CPU Time | (C) Time spent by the processor executing the program's instructions | | Elapsed Time | (B) Total wall-clock time from job start to job end, including waits | | I/O Wait Time | (D) Time the program spends waiting for I/O operations to complete | | EXCP Count | (A) The number of physical I/O operations performed by a program | | TCB Time | (E) CPU time consumed under the program's Task Control Block | | SRB Time | (F) CPU time consumed under a Service Request Block for system services |

Exercise 2: Compiler Options for Performance

Problem: For each of the following COBOL compiler options, state whether it improves or degrades runtime performance and briefly explain why.

  1. OPTIMIZE(FULL) vs. OPTIMIZE(0)
  2. TRUNC(OPT) vs. TRUNC(STD)
  3. NUMPROC(PFD) vs. NUMPROC(NOPFD)
  4. FASTSRT vs. NOFASTSRT
  5. NOTEST vs. TEST
Solution 1. **OPTIMIZE(FULL) — Improves performance.** The compiler applies advanced optimization techniques including dead code elimination, common subexpression elimination, loop optimization, and instruction scheduling. `OPTIMIZE(0)` performs minimal optimization, resulting in more straightforward but slower object code. 2. **TRUNC(OPT) — Improves performance.** With `TRUNC(OPT)`, the compiler generates the most efficient code for binary (COMP) data items, truncating to the optimal machine representation. `TRUNC(STD)` truncates to the PICTURE clause size, requiring additional instructions. However, `TRUNC(OPT)` assumes the program uses binary fields correctly — values must not exceed the PICTURE clause range. 3. **NUMPROC(PFD) — Improves performance.** With `NUMPROC(PFD)` (Preferred sign), the compiler assumes packed decimal and zoned decimal signs are always valid and skips sign validation/correction. `NUMPROC(NOPFD)` generates extra instructions to check and fix signs on every arithmetic operation. PFD can be used when all numeric data comes from trusted sources. 4. **FASTSRT — Improves performance.** When a COBOL program uses SORT, `FASTSRT` allows DFSORT to directly read the input file and write the output file, bypassing the COBOL I/O routines. This eliminates the overhead of passing records between DFSORT and the COBOL program through the INPUT PROCEDURE/OUTPUT PROCEDURE interface. 5. **NOTEST — Improves performance.** `NOTEST` eliminates debugging hooks and symbol tables from the generated code, resulting in smaller and faster executable modules. `TEST` inserts debugging infrastructure that adds CPU overhead even when no debugger is attached.

Exercise 3: Block Size Impact on I/O

Problem: A batch COBOL program reads a sequential file with RECFM=FB, LRECL=200, and the following block sizes on different test runs:

Run BLKSIZE Records/Block
A 200 1
B 6,000 30
C 27,800 139

The file contains 10,000,000 records. Calculate the number of physical I/O operations (EXCPs) for each run, and determine the percentage improvement from Run A to Run C.

Solution **Run A (BLKSIZE=200, 1 record/block):** - EXCPs = 10,000,000 / 1 = 10,000,000 **Run B (BLKSIZE=6000, 30 records/block):** - EXCPs = 10,000,000 / 30 = 333,334 (rounded up) **Run C (BLKSIZE=27800, 139 records/block):** - EXCPs = 10,000,000 / 139 = 71,943 (rounded up) **Improvement from Run A to Run C:** - Reduction: 10,000,000 - 71,943 = 9,928,057 fewer EXCPs - Percentage improvement: (9,928,057 / 10,000,000) x 100 = 99.3% This demonstrates why block size optimization is one of the most impactful performance improvements for batch COBOL programs. Each EXCP involves channel program setup, device scheduling, and interrupt processing — overhead that is independent of block size. By reading 139 records per I/O instead of 1, we eliminate 99.3% of this overhead.

Exercise 4: VSAM Tuning Parameters

Problem: Name four VSAM tuning parameters that can be specified either in the IDCAMS DEFINE CLUSTER or at runtime via the JCL DD statement, and explain how each affects performance.

Hint Consider parameters related to buffering (both data and index components), control interval size, free space distribution, and share options. Think about which parameters affect read performance versus write/update performance.

Exercise 5: DB2 Performance Indicators

Problem: List five DB2 performance metrics that a COBOL programmer should monitor, and for each, describe what a poor value indicates about the program's SQL efficiency.

Hint Think about metrics related to: the number of SQL calls versus rows returned (getpage ratio), synchronous I/O versus buffer pool reads, lock contention, sort operations, and the ratio of sequential prefetch to random I/O. DB2 provides these through EXPLAIN, accounting traces, and statistics traces.

Tier 2 — Understand

Exercise 6: CPU-Bound vs. I/O-Bound Programs

Explain the difference between a CPU-bound and an I/O-bound COBOL program. For each type, describe: 1. What the SMF/RMF metrics look like. 2. What the primary performance bottleneck is. 3. What tuning strategies are most effective.

Give an example of a financial application that would be CPU-bound and one that would be I/O-bound.


Exercise 7: OPTIMIZE Compiler Option Trade-offs

Explain why the OPTIMIZE(FULL) compiler option is not always used in development but is recommended for production. Address: 1. The impact on compile time. 2. The impact on debugging capability. 3. The types of optimizations performed. 4. Potential risks if the source code contains data definition errors.


Exercise 8: VSAM CI and CA Splits

Explain what happens during a VSAM Control Interval (CI) split and a Control Area (CA) split. Why do splits degrade performance? How does the FREESPACE parameter prevent splits, and what is the trade-off of specifying too much free space?


Exercise 9: Sequential vs. Random VSAM Access Performance

A COBOL program needs to update 500,000 records in a VSAM KSDS containing 5,000,000 records. The updates are to records scattered uniformly across the file. Compare the performance characteristics of:

  1. Reading the update file, sorting it by key, then processing the KSDS sequentially.
  2. Reading each update record and performing a random READ/REWRITE against the KSDS.

Which approach is faster and why? Under what circumstances might the other approach be acceptable?


Exercise 10: Understanding DFSORT FASTSRT

Explain how the COBOL FASTSRT compiler option changes the behavior of a SORT statement in a COBOL program. Draw a diagram (described textually) showing the data flow with and without FASTSRT. Why does this matter for a banking application that sorts millions of transactions nightly?


Tier 3 — Apply

Exercise 11: Optimizing a COBOL Arithmetic Routine

The following COBOL code calculates compound interest for each account in a 10-million-record file. Rewrite it for maximum performance:

       PERFORM VARYING WS-MONTH FROM 1 BY 1
           UNTIL WS-MONTH > 12
           COMPUTE WS-BALANCE =
               WS-BALANCE * (1 + (WS-ANNUAL-RATE / 12))
       END-PERFORM.

Identify three specific performance improvements and rewrite the code.


Exercise 12: File I/O Optimization

A COBOL batch program processes a daily transaction file (FB, LRECL=300, 5 million records) and updates a master file (VSAM KSDS, 20 million records). The current JCL uses default buffering:

//TRANIN   DD  DSN=BANK.PROD.TRANFILE,DISP=SHR
//MASTER   DD  DSN=BANK.PROD.ACCTMSTR,DISP=SHR

Rewrite the DD statements with optimal buffering parameters. Explain each parameter choice and estimate the performance improvement.


Exercise 13: DB2 SQL Optimization

The following COBOL-DB2 code retrieves account information. Rewrite it for optimal DB2 performance:

       PERFORM UNTIL END-OF-TRAN-FILE
           READ TRAN-FILE INTO WS-TRAN-REC
               AT END SET END-OF-TRAN-FILE TO TRUE
           END-READ

           EXEC SQL
               SELECT *
                 FROM ACCOUNT_MASTER
                WHERE ACCT_NUMBER = :WS-TRAN-ACCT
           END-EXEC

           IF SQLCODE = 0
               EXEC SQL
                   SELECT CUST_NAME, CUST_ADDR, CUST_PHONE,
                          CUST_EMAIL, CUST_SSN, CUST_DOB
                     FROM CUSTOMER_MASTER
                    WHERE CUST_ID = :WS-CUST-ID
               END-EXEC
           END-IF

           PERFORM PROCESS-TRANSACTION
       END-PERFORM.

Identify at least four SQL performance problems and provide the optimized code.


Exercise 14: CICS Performance Tuning

A CICS online inquiry transaction takes 2.5 seconds to respond, with a target of 0.5 seconds. The transaction:

  1. Receives a BMS map with an account number.
  2. Reads the VSAM account master (random by key).
  3. Reads 3 related VSAM files (transaction history, customer detail, product info).
  4. Formats and sends a response BMS map.

The CICS monitoring data shows: - Total CPU: 0.15 seconds - Total suspend time: 2.1 seconds - File I/O wait: 1.8 seconds - Number of file reads: 4

Analyze the bottleneck and write the optimized COBOL code and JCL changes to meet the target response time.


Exercise 15: Memory Layout Optimization

The following WORKING-STORAGE section is used in a high-performance batch program that processes 50 million records. Reorganize it for optimal memory access patterns:

       WORKING-STORAGE SECTION.
       01  WS-COUNTERS.
           05  WS-READ-COUNT      PIC 9(9)  COMP.
           05  WS-ERROR-MSG       PIC X(200).
           05  WS-WRITE-COUNT     PIC 9(9)  COMP.
           05  WS-REPORT-LINE     PIC X(133).
           05  WS-PROCESS-COUNT   PIC 9(9)  COMP.
           05  WS-WORK-AREA       PIC X(500).
           05  WS-SKIP-COUNT      PIC 9(9)  COMP.
           05  WS-TABLE-AREA.
               10  WS-TABLE-ENTRY OCCURS 10000 TIMES.
                   15  WS-TBL-KEY    PIC X(12).
                   15  WS-TBL-DATA   PIC X(50).
           05  WS-TOTAL-AMT       PIC S9(13)V99 COMP-3.

Explain the principles of memory layout optimization for COBOL and show the reorganized layout.


Exercise 16: Batch Job Optimization

A nightly batch cycle runs 5 sequential steps:

Step Program Input File Output File CPU (min) Elapsed (min)
1 EXTRACT VSAM Master EXTRACT.FILE 5 45
2 SORT EXTRACT.FILE SORTED.FILE 3 20
3 UPDATE SORTED.FILE + Master Updated Master 8 60
4 REPORT1 Updated Master REPORT.DAILY 2 15
5 REPORT2 Updated Master REPORT.SUMMARY 1 10

Total elapsed: 150 minutes. Target: 90 minutes. Identify optimization opportunities and redesign the batch flow.


Exercise 17: VSAM Tuning for Online Performance

A VSAM KSDS serving a CICS online application has the following characteristics from LISTCAT:

RECORDS-TOTAL:          5,000,000
CI-SIZE-DATA:           4,096
CI-SIZE-INDEX:          2,048
FREESPACE-CI%:          0
FREESPACE-CA%:          0
SPLITS-CI:              850,000
SPLITS-CA:              15,000
EXTENTS:                115
BUFND:                  2
BUFNI:                  1
AVERAGE-RECORD-SIZE:    350
MAXIMUM-RECORD-SIZE:    500

Write the IDCAMS commands and JCL changes to reorganize and tune this VSAM file for optimal online performance. Justify each parameter choice.


Tier 4 — Analyze

Exercise 18: Production Performance Degradation Analysis

A production COBOL batch job that normally runs in 2 hours has gradually increased to 6 hours over the past 3 months. No code changes have been made. Analyze the following clues and identify the root causes:

  • VSAM LISTCAT shows CI splits have grown from 10,000 to 2,000,000.
  • The input sequential file has grown from 1 million to 8 million records.
  • SMF data shows CPU time increased from 15 minutes to 25 minutes.
  • SMF data shows I/O wait time increased from 90 minutes to 320 minutes.
  • The VSAM file has gone from 5 extents to 123 extents.
  • Block size of the sequential file has remained at 6,160 for LRECL=80.

Identify each contributing factor, quantify its impact where possible, and provide specific corrective actions in priority order.


Exercise 19: Compiler Option Impact Analysis

A COBOL program is compiled with the following options:

OPTIMIZE(0),TRUNC(STD),NUMPROC(NOPFD),NOFASTSRT,TEST,SSRANGE

The program is an overnight batch process that: - Reads 20 million transaction records - Performs packed decimal arithmetic on each record - SORTs the transactions by account number using INPUT/OUTPUT PROCEDURE - Updates 5 million VSAM master records

Analyze the performance impact of each compiler option and estimate the total improvement from switching to the optimal production settings. Provide the recommended compiler options string and justify each choice.


Exercise 20: DB2 Access Path Analysis

A COBOL-DB2 program executes the following SQL statement 2 million times during a batch run:

       EXEC SQL
           SELECT ACCT_BALANCE, ACCT_STATUS, LAST_ACTIVITY_DATE
             FROM ACCOUNT_MASTER
            WHERE BRANCH_CODE = :WS-BRANCH
              AND ACCT_TYPE = :WS-TYPE
              AND ACCT_STATUS = 'A'
            ORDER BY ACCT_BALANCE DESC
       END-EXEC

The DB2 EXPLAIN output shows:

ACCESS TYPE: TABLE SPACE SCAN
MATCHING COLUMNS: 0
INDEX USED: (NONE)
SORT REQUIRED: YES
ESTIMATED COST: 85,000

Analyze the access path, explain why it is inefficient, design the optimal index, and estimate the performance improvement.


Exercise 21: CICS Transaction Response Time Breakdown

A CICS transaction performance report shows:

Component Time (ms)
Dispatch Time (CPU) 12
VSAM File I/O 180
DB2 Elapsed 450
BMS Send/Receive 30
ENQ/DEQ Wait 800
Other Suspend 28
Total Response 1,500

Analyze each component. What is the primary bottleneck? What could cause high ENQ/DEQ wait time? Propose specific tuning actions for each component, prioritized by expected impact.


Exercise 22: Batch Window Compression Analysis

A bank's nightly batch window is 6 hours (10 PM to 4 AM), and the current batch cycle takes 5 hours 45 minutes. A new regulatory requirement adds two more batch jobs estimated at 30 minutes each. Analyze the following approaches to fit everything within the window:

  1. Parallelizing independent job streams.
  2. Optimizing existing job I/O (block size, buffering).
  3. Replacing COBOL SORT with DFSORT FASTSRT.
  4. Consolidating multiple sequential file passes into single-pass processing.
  5. Moving non-critical jobs outside the batch window.

For each approach, estimate the time savings and implementation effort. Propose a comprehensive plan.


Exercise 23: Memory Utilization Analysis

A COBOL program uses the following data structures:

       01  WS-ACCOUNT-TABLE.
           05  WS-ACCT-ENTRY OCCURS 1000000 TIMES
               INDEXED BY WS-ACCT-IDX.
               10  WS-ACCT-NUM   PIC X(12).
               10  WS-ACCT-BAL   PIC S9(13)V99 COMP-3.
               10  WS-ACCT-NAME  PIC X(50).
               10  WS-ACCT-FILLER PIC X(26).

Calculate the total memory consumed by this table. Analyze whether this is appropriate for a batch program and for a CICS program. Propose alternative approaches if the memory usage is excessive, such as VSAM file-based lookups, DB2 table access, or binary search with a smaller table.


Tier 5 — Create

Exercise 24: Comprehensive Performance Tuning Playbook

Create a performance tuning playbook for a banking COBOL application environment. The playbook should provide step-by-step procedures for:

  1. Baseline Establishment: How to capture and document current performance metrics for all critical jobs using SMF, RMF, and CICS monitoring data.
  2. Problem Identification: Decision tree for diagnosing whether a job is CPU-bound, I/O-bound, or contention-bound.
  3. Compiler Optimization: Checklist of compiler options to review with recommended production settings and justification for each.
  4. File I/O Optimization: Standards for block size selection, buffering, and VSAM tuning for both batch and online.
  5. DB2 Optimization: SQL review checklist, index design guidelines, and EXPLAIN analysis procedures.
  6. CICS Optimization: Transaction response time breakdown procedures and tuning parameters.

Include sample JCL, COBOL code examples, and monitoring commands for each section.


Exercise 25: Automated Performance Monitoring and Alerting System

Design and write a COBOL-based batch performance monitoring system that:

  1. Reads SMF Type 30 records (job accounting) for all COBOL batch jobs.
  2. Compares actual CPU time, elapsed time, and EXCP counts against established baselines stored in a VSAM reference file.
  3. Flags jobs that exceed baselines by more than 20% (warning) or 50% (critical).
  4. Generates a performance trend report showing week-over-week changes.
  5. Produces actionable alerts with specific tuning recommendations based on the type of degradation detected.
  6. Maintains a history file for long-term trend analysis.

Write the COBOL program (including SMF record layouts), the VSAM baseline file definition, the JCL to run the system, and sample output for each report type.


Exercise 26: File I/O Performance Benchmark Suite

Create a COBOL benchmark program that measures and compares I/O performance across different configurations:

  1. Sequential file read performance at block sizes of 800, 6,400, 27,800, and 32,760.
  2. VSAM KSDS random read performance at CI sizes of 2,048, 4,096, 8,192, and 16,384.
  3. VSAM sequential read performance with buffer counts of 2, 5, 10, and 20.
  4. Comparison of QSAM vs. BSAM for sequential processing.

The benchmark should: - Use COBOL FUNCTION CURRENT-DATE for timing. - Process a configurable number of records (default 1,000,000). - Produce a formatted comparison report with records/second metrics. - Include JCL to create test data and run each benchmark configuration.

Write the complete COBOL program, JCL for test data creation, and JCL for each benchmark run.


Exercise 27: DB2 SQL Performance Optimization Toolkit

Design a suite of COBOL programs that analyze and optimize DB2 SQL performance:

  1. SQL Analyzer: A COBOL program that reads the DB2 PLAN_TABLE (EXPLAIN output) and identifies SQL statements with: tablespace scans, missing indexes, sorts, and high estimated costs. Produces a prioritized optimization report.

  2. Index Advisor: Given a set of SQL statements extracted from COBOL programs, recommends optimal indexes by analyzing WHERE clauses, JOIN conditions, and ORDER BY columns.

  3. Batch SQL Optimizer: Rewrites common inefficient SQL patterns found in COBOL programs: - SELECT * to explicit column lists - Singleton SELECTs in loops to cursor-based processing - Correlated subqueries to JOINs - Missing host variable declarations

Write the COBOL programs with complete SQL, the JCL to run each tool, and sample reports.


Exercise 28: End-to-End Batch Performance Optimization Project

A bank's month-end batch processing takes 14 hours and must be reduced to 8 hours. The batch consists of 200 jobs across 15 job streams. You have the following data:

Top 10 longest-running jobs:

Job Steps CPU (min) Elapsed (min) EXCPs (M) Description
GLPOST 5 45 180 12.5 GL posting
INTCALC 3 90 150 3.2 Interest calc
STMTGEN 8 30 120 18.0 Statement gen
LOANUPD 4 35 100 8.5 Loan updates
RPTMSTR 12 15 90 22.0 Master reports
RECONCL 6 25 85 5.0 Reconciliation
ARCHVNG 3 10 75 15.0 Archival
TAXCALC 2 60 70 1.5 Tax calculation
REGFEED 4 20 65 9.0 Regulatory feed
AUDITEX 7 12 60 11.0 Audit extract

Design a comprehensive optimization plan that includes:

  1. Analysis of each job to determine if it is CPU-bound or I/O-bound.
  2. Specific optimization recommendations for each job.
  3. A redesigned batch schedule with parallelism.
  4. Estimated time savings for each optimization.
  5. Implementation priority and risk assessment.
  6. Before/after JCL for the top 3 jobs.

Exercise 29: COBOL Code Performance Refactoring Guide

Create a guide of 15 COBOL code patterns that impact performance, with before and after examples:

  1. Inefficient PERFORM loops (nested PERFORMs with redundant processing).
  2. Suboptimal data type usage (DISPLAY vs. COMP vs. COMP-3).
  3. String manipulation inefficiencies (INSPECT vs. reference modification).
  4. Table search optimization (sequential SEARCH vs. SEARCH ALL vs. direct index).
  5. Arithmetic operation optimization (COMPUTE vs. individual statements).
  6. Conditional logic optimization (EVALUATE vs. nested IF, condition ordering).
  7. File I/O patterns (single-record processing vs. block processing).
  8. SORT optimization (internal vs. external, USING/GIVING vs. INPUT/OUTPUT PROCEDURE).
  9. CALL overhead (static vs. dynamic, parameter passing efficiency).
  10. Working-Storage vs. Local-Storage performance in CICS.
  11. DB2 cursor management (OPEN/FETCH/CLOSE placement).
  12. CICS command optimization (READ vs. READNEXT, LENGTH specification).
  13. Packed decimal vs. binary for counters and subscripts.
  14. Efficient use of INITIALIZE vs. MOVE SPACES/ZEROS.
  15. Reducing program size through efficient copybook usage.

For each pattern, provide: the performance problem description, the "before" COBOL code, the "after" COBOL code, the estimated performance improvement, and when the optimization matters most.


Exercise 30: Real-Time Performance Dashboard for COBOL Batch Processing

Design and implement a performance monitoring dashboard that provides real-time visibility into COBOL batch job execution:

  1. Data Collection: A COBOL program that reads SMF records in near-real-time and writes key metrics to a shared VSAM file.

  2. Dashboard Display: A CICS transaction that displays: - Currently running batch jobs with percent complete - CPU and elapsed time versus baseline - I/O rates (EXCPs per second) - Projected completion time - Alert indicators for jobs running behind schedule

  3. Historical Analysis: A batch program that produces: - Week-over-week performance trends - Resource utilization heat maps (described as formatted reports) - Capacity planning projections

  4. Alert Engine: Logic that detects: - Jobs exceeding time thresholds - Abnormal EXCP rates indicating I/O problems - CPU spikes suggesting infinite loops or runaway processes

Write the COBOL programs for data collection and dashboard display, the CICS BMS maps, the VSAM file definitions, and the JCL for the entire system. Include the complete record layouts and processing logic.