skip to Main Content

I have an old legacy service for benchmarking a load produced by html5-pages to the users hardware. Here is a high-level idea: we want to be sure that some specific web-page will not freeze users browser and laptop with heavy CPU load.

The way it is implemented now: there is a physical laptop (sic!) in the office with the python script, which takes some html-file (let’s omit a description of the way the file gets to this laptop for simplification) and opens it in Google Chrome (in headless mode) and makes 100 CPU measurements per second during 30 seconds interval.

The most important part of measurement function (simplified):

for p in psutil.process_iter():
    cpu_percent = p.cpu_percent(interval=collect_stats_interval)

So the key idea is quite simple: we have kind of "average" users laptop, and we open some page in most popular browser in this laptop. And if on this laptop with this page opened the CPU load is below 40%, it means that on the average users laptop this page will also generate nearly the same load and it is ok.

In other words, if we opened this page on our laptop and it is ok, the users laptop will be ok too.

And now I have to move this code to a bit more solid and robust infrastructure than a laptop in office. AND, it is crucial, to keep measurements proportions.

I mean, if some html5 page had been benchmarked to 35%, on the new infrastructure we need to approximate all results. Like "On this brand new high-performance server this page has been benchmarked to 5% CPU usage, and so it means that on a simple users laptop (old approach) this page will make 35% CPU load".

But here is the first problem: it seems like I cannot use this approach inside any kind of virtual infrastructure and keep measurements stable.

I’ve tried to run this service inside a docker and despite all tricks with cpu limits all I’ve got is unstable and big measurements range: first time it is 20%, than -40%, next time – 33%.

And since on the laptop (without any virtualisation) this service worked well and always provided stable measurements, I believe that the key problem is virtualisation.

I think so because dedicated virtual machine with Ubuntu without docker had provided me with nothing more than the same unstable bunch of measurements.

And that’s why I have the second problem: without stable measurements I cannot develop some new-to-old mapping method.

Also I’m not good at system programming so I have no clear understanding of CPU load concept. I mean, what I have to measure to be sure that some software makes "moderate" CPU load on some users hardware? Maybe there is a better and robust way to measure this metric – maybe CPU time, maybe something else.



And (finally!) here is the question: what is the most robust and portable way to measure CPU load across bare metal hardware and some k8s/virtual machine? What I have to measure and how?

2

Answers


  1. Unfortunately, I think you’re right with this point:

    I cannot use this approach inside any kind of virtual infrastructure

    If you’re running on virtual infrastructure, then a hypervisor determines the amount of CPU cycles that your test environment can use. From within the test system, you can neither tell the number of "real" CPU cycles that you consumed, nor the total number of CPU resources that were potentially available for your system.

    That is, in general, you will need to check the CPU load measurement features offered by the hypervisor that provides your virtual infrastructure. Your other option is sticking with physical infrastructure.

    (Virtualization in this context applies to virtual infrastructure. If you’re running containers on physical infrastructure then the load measurement situation will be straightforward, but I understood that this is not your current setup.)

    Login or Signup to reply.
  2. Измерение нагрузки процессора на различных платформах и виртуальных средах может быть сложной задачей, особенно если вы стремитесь к стабильным и надежным результатам. Ваша задача состоит в том, чтобы удостовериться, что веб-страница не вызовет значительной загрузки процессора на разных устройствах и средах. Вот несколько рекомендаций и способов для измерения нагрузки процессора:

    Использование контейнеров: Если вы хотите использовать Docker, убедитесь, что у вас правильно настроены ресурсы контейнера и ограничения CPU. Вы можете использовать флаги –cpu и –cpuset-cpus для задания лимитов CPU. Это может помочь в стабилизации измерений внутри контейнера.

    Виртуальные машины (VM): Если вы работаете с виртуальными машинами, убедитесь, что ваши VM имеют надлежащие ресурсы, и вы можете использовать инструменты управления ресурсами на уровне хоста для ограничения доступа к CPU. Например, в VMware ESXi это можно сделать через настройки ресурсов.

    Измерение загрузки CPU: Для измерения нагрузки CPU можно использовать различные инструменты. Вместо библиотеки psutil можно рассмотреть более низкоуровневые инструменты, такие как perf или top, для получения более точных данных о нагрузке на CPU. Они могут предоставить более стабильные результаты.

    Управление фоновыми процессами: Убедитесь, что в системе нет других фоновых процессов, которые могли бы влиять на нагрузку процессора. Вы можете использовать инструменты, такие как nice и renice, чтобы управлять приоритетами процессов и уменьшить влияние фоновых задач.

    Генерация нагрузки: Для надежных измерений, возможно, вам потребуется разработать специальный бенчмарк или тестовое приложение, которое создает нагрузку на CPU в контролируемой среде. Это позволит вам получить стабильные результаты, которые можно сравнить с вашим старым методом измерения на ноутбуке.

    Автоматизация и сравнение: Автоматизируйте процесс измерения нагрузки процессора на разных платформах и виртуальных средах. Сравните результаты с теми, которые вы получили на ноутбуке, чтобы удостовериться, что процент нагрузки остается сопоставимым.

    Мониторинг в реальном времени: Рассмотрите использование инструментов мониторинга, таких как Prometheus или Grafana, для получения данных о нагрузке на процессор в реальном времени. Это позволит вам следить за изменениями в нагрузке на протяжении длительного времени.

    Помимо этого, убедитесь, что ваш тестовый скрипт или приложение хорошо оптимизированы, чтобы точно отражать реальные условия использования веб-страницы на устройствах пользователей.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search