C Online Compiler
Example: Call Rate Monitor in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Call Rate Monitor #include <stdio.h> #include <time.h> // For time(), difftime() #include <unistd.h> // For usleep() on Unix-like systems, or <windows.h> and Sleep() on Windows // Global counter for calls (volatile to prevent compiler optimizations that might affect reads) static volatile long long call_count = 0; // Global variable to store the start time for rate calculation static time_t monitor_start_time; void monitored_function_with_rate() { call_count++; // Simulate some work done by the function // For a real scenario, this would be your actual function logic. } void initialize_call_rate_monitor() { call_count = 0; monitor_start_time = time(NULL); // Get current time in seconds } void report_current_call_rate() { time_t current_time = time(NULL); double elapsed_seconds = difftime(current_time, monitor_start_time); printf("--- Call Rate Report ---\n"); printf("Current Call Count: %lld\n", call_count); if (elapsed_seconds > 0) { double rate = (double)call_count / elapsed_seconds; printf("Elapsed Time: %.0f seconds\n", elapsed_seconds); printf("Calculated Call Rate: %.2f calls/second\n", rate); } else { printf("Not enough time has elapsed (less than 1 second) to calculate a meaningful rate.\n"); } printf("------------------------\n"); } int main() { // Step 1: Initialize the monitoring system initialize_call_rate_monitor(); // Step 2: Simulate calls to the monitored function over a duration printf("Simulating function calls for 5 seconds...\n"); time_t simulation_start_wall = time(NULL); while (difftime(time(NULL), simulation_start_wall) < 5) { // Run for 5 wall-clock seconds monitored_function_with_rate(); // A small delay to avoid excessive CPU usage if the function does very little. // For pushing maximum call rates, remove usleep. // usleep(1); // Sleep for 1 microsecond (requires unistd.h) } // Step 3: Report the call rate for the first interval report_current_call_rate(); // Step 4: Reset and simulate for another interval printf("\nResetting monitor and simulating more calls for 3 seconds...\n"); initialize_call_rate_monitor(); // Reset monitor for a new interval simulation_start_wall = time(NULL); while (difftime(time(NULL), simulation_start_wall) < 3) { // Run for another 3 wall-clock seconds monitored_function_with_rate(); // usleep(1); } // Step 5: Report the call rate for the second interval report_current_call_rate(); return 0; }
Output
Clear
ADVERTISEMENTS