import time

def cpu_monitor():
while True:
current_time = time.strftime('%H:%M:%S', time.localtime())
cpu_usage = round(100.0 * (time.perf_counter() - start_time)/(time.perf_counter() - start_time), 2)
print(f"{current_time} 秒 {cpu_usage:.2f} 个 CPU 核心使用率")
time.sleep(1)

if name == 'main':
cpu_monitor()

一个监控服务器CPU的代码_获取当前时间

在这个示例中,我们定义了一个名为cpu_monitor()的函数,该函数使用一个无限循环来不断记录服务器CPU的使用情况。在每次循环中,我们使用time.perf_counter()函数获取当前时间戳,并计算出当前CPU的使用率。然后,我们将使用率输出到控制台上,并使用time.sleep()函数暂停一秒钟,以便我们可以看到使用率的变化。

main()函数中,我们调用cpu_monitor()函数来启动监控服务器CPU的监控。