| | import time |
| | import random |
| | import math |
| | from itertools import cycle |
| |
|
| | def cpu_intensive_task(): |
| | """随机选择一个CPU密集型任务执行""" |
| | tasks = [ |
| | _calculate_primes, |
| | _matrix_multiplication, |
| | _fibonacci_calculation, |
| | _pi_calculation |
| | ] |
| | task = random.choice(tasks) |
| | task() |
| |
|
| | def _calculate_primes(): |
| | """计算质数""" |
| | n = random.randint(100000, 1000000) |
| | sieve = [True] * (n + 1) |
| | sieve[0:2] = [False, False] |
| | for i in range(2, int(math.sqrt(n)) + 1): |
| | if sieve[i]: |
| | sieve[i*i : n+1 : i] = [False] * len(sieve[i*i : n+1 : i]) |
| |
|
| | def _matrix_multiplication(): |
| | """矩阵乘法""" |
| | size = random.randint(100, 300) |
| | matrix = [[random.random() for _ in range(size)] for _ in range(size)] |
| | result = [[0] * size for _ in range(size)] |
| | for i in range(size): |
| | for j in range(size): |
| | for k in range(size): |
| | result[i][j] += matrix[i][k] * matrix[k][j] |
| |
|
| | def _fibonacci_calculation(): |
| | """斐波那契数列计算""" |
| | n = random.randint(300000, 500000) |
| | a, b = 0, 1 |
| | for _ in range(n): |
| | a, b = b, a + b |
| |
|
| | def _pi_calculation(): |
| | """蒙特卡洛法计算π近似值""" |
| | iterations = 10000000 |
| | count = 0 |
| | for _ in range(iterations): |
| | x = random.random() |
| | y = random.random() |
| | if x*x + y*y <= 1: |
| | count += 1 |
| | pi = 4 * count / iterations |
| |
|
| | def main(): |
| | try: |
| | |
| | initial_delay = random.randint(5, 15) |
| | time.sleep(initial_delay * 60) |
| | |
| | |
| | intervals = cycle([random.randint(10, 300) for _ in range(50)]) |
| | |
| | while True: |
| | start_time = time.time() |
| | print(f"开始CPU密集型任务 @ {time.strftime('%Y-%m-%d %H:%M:%S')}") |
| | |
| | cpu_intensive_task() |
| | |
| | elapsed = time.time() - start_time |
| | print(f"任务完成,耗时: {elapsed:.2f}秒") |
| | |
| | |
| | delay = next(intervals) |
| | print(f"下次任务将在 {delay} 分钟后执行...") |
| | time.sleep(delay * 60) |
| | |
| | except KeyboardInterrupt: |
| | print("\n任务调度已停止") |
| |
|
| | if __name__ == "__main__": |
| | main() |
| |
|