This document provides an overview of PHP memory usage and management. It introduces key concepts like the Zend Memory Manager (ZendMM), which handles memory allocation and freeing for each PHP request. The document demonstrates how to monitor memory usage from PHP using functions like memory_get_usage() and from the OS perspective using /proc. It also discusses potential memory issues like references and circular references, and how to track reference counts. The goal is to help understand and optimize PHP memory consumption.
This is a presentation which describe the big picture of the Rest API. In this presentation I simply describe the theories with practical examples. Hope this presentation will cover the overall Rest API domain.
Use Cases for Elastic Search PercolatorMaxim Shelest
Overview of possible Use Cases for Elastic Search Percolator. Deep dive into Percolator feature of Elasticsearch with various examples for source code, HTTP requests and architecture.
This lecture discusses the different techniques used to install, uninstall and upgrade software packages in Linux and the associated tools
Video for this lecture on youtube:
http://www.youtube.com/watch?v=pFqdupd9wKk
Check the other Lectures and courses in
http://Linux4EnbeddedSystems.com
or Follow our Facebook Group at
- Facebook: @LinuxforEmbeddedSystems
Lecturer Profile:
Ahmed ElArabawy
- https://www.linkedin.com/in/ahmedelarabawy
This is a presentation which describe the big picture of the Rest API. In this presentation I simply describe the theories with practical examples. Hope this presentation will cover the overall Rest API domain.
Use Cases for Elastic Search PercolatorMaxim Shelest
Overview of possible Use Cases for Elastic Search Percolator. Deep dive into Percolator feature of Elasticsearch with various examples for source code, HTTP requests and architecture.
This lecture discusses the different techniques used to install, uninstall and upgrade software packages in Linux and the associated tools
Video for this lecture on youtube:
http://www.youtube.com/watch?v=pFqdupd9wKk
Check the other Lectures and courses in
http://Linux4EnbeddedSystems.com
or Follow our Facebook Group at
- Facebook: @LinuxforEmbeddedSystems
Lecturer Profile:
Ahmed ElArabawy
- https://www.linkedin.com/in/ahmedelarabawy
A tutorial about CodeIgniter. It's purpose is to help someone with no prior knowledge of frameworks, to understand it's basic principles and how it works.
In this C# Web REST tutorial, beginners will learn first what a C# REST API is and then what are the HTTP Verbs in C# REST API is. Learn about the HTTP Status Codes in this C# tutorial. and we will become acquainted with all of the Constraints of the C# REST API. After that, for a better learning experience, we will see a practical demonstration of C# REST API in this C# programming tutorial. Finally we will wind up this session with Few takeaways on C# REST API.
NPM is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client, also called npm, and an online database of public and paid-for private packages, called the npm registry.
This is an introductory presentation on Svelte ( Svelte 3) .
Outline is as follows:
Introduction
High level Comparison with A, R, V
History of Svelte
What is Svelte?
Features of Svelte
Lifecycle Hooks
Store with a Demo
Drawbacks of Svelte
Demo
Conclusion
Video on Youtube: https://www.youtube.com/watch?v=76hQBnjhVdY&feature=youtu.be
Whether it is providing reusable templates and components, code optimization and debugging, streamlining developer’s workflow and productivity, latest web development tools are all about making the lives of developers easy and efficient. Frontend development tools have witnessed rapid progress and growth.
Presentation given at Config Management Camp 2018 in the Foreman track.
It gives brief introduction about Foreman Maintain tool which provides simplified upgrade process for foreman instance. Also, explains using this tool how you keep foreman up and running in healthy state.
Grafana and AWS - Implementation and UsageManish Chopra
This article provides a use case scenario of Grafana on AWS (Amazon Web Services). It demonstrates a brief implementation of Grafana as a Docker container, and connects to Amazon Cloudwatch data source. It then monitors events and allows visualizing using native methods and customization. Grafana can be setup in production as given in the document.
PHP may seem to be a very easy language but many of don't know how PHP works. We will discuss the less known facts about PHP and we will also cover some common type of software design patterns used with PHP
A tutorial about CodeIgniter. It's purpose is to help someone with no prior knowledge of frameworks, to understand it's basic principles and how it works.
In this C# Web REST tutorial, beginners will learn first what a C# REST API is and then what are the HTTP Verbs in C# REST API is. Learn about the HTTP Status Codes in this C# tutorial. and we will become acquainted with all of the Constraints of the C# REST API. After that, for a better learning experience, we will see a practical demonstration of C# REST API in this C# programming tutorial. Finally we will wind up this session with Few takeaways on C# REST API.
NPM is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client, also called npm, and an online database of public and paid-for private packages, called the npm registry.
This is an introductory presentation on Svelte ( Svelte 3) .
Outline is as follows:
Introduction
High level Comparison with A, R, V
History of Svelte
What is Svelte?
Features of Svelte
Lifecycle Hooks
Store with a Demo
Drawbacks of Svelte
Demo
Conclusion
Video on Youtube: https://www.youtube.com/watch?v=76hQBnjhVdY&feature=youtu.be
Whether it is providing reusable templates and components, code optimization and debugging, streamlining developer’s workflow and productivity, latest web development tools are all about making the lives of developers easy and efficient. Frontend development tools have witnessed rapid progress and growth.
Presentation given at Config Management Camp 2018 in the Foreman track.
It gives brief introduction about Foreman Maintain tool which provides simplified upgrade process for foreman instance. Also, explains using this tool how you keep foreman up and running in healthy state.
Grafana and AWS - Implementation and UsageManish Chopra
This article provides a use case scenario of Grafana on AWS (Amazon Web Services). It demonstrates a brief implementation of Grafana as a Docker container, and connects to Amazon Cloudwatch data source. It then monitors events and allows visualizing using native methods and customization. Grafana can be setup in production as given in the document.
PHP may seem to be a very easy language but many of don't know how PHP works. We will discuss the less known facts about PHP and we will also cover some common type of software design patterns used with PHP
PHP is one of the most popular open source programming languages in the world. It powers some of the highest traffic sites in the world, and at the same time it powers some of the lowest traffic sites in the world. But have you ever wondered how it works under the hood? Have you been overwelmed by the thought of looking at the C code that runs PHP? Well, this talk is for you!
We're going to explore how PHP works under the hood, by looking at a PHP implementation of it: PHPPHP! Have you ever wondered what an OPCODE Cache is really doing? Have you ever wondered what a T_PAAMAYIM_NEKUDOTAYIM is? Have you ever wondered why an interpreted languages has a compiler? We'll explore all of these topics, and more! And the best part of it all? You don't need to know C to understand the details! Using PHPPHP, we can explore the language details in a high level language, where things like memory management don't get in the way of the real content. If you've ever wanted to know how PHP works, this is the talk for you!
ارائه «گزارشی از برنامهنویسی موازی در پیاچپی» در اولین همایش پیاچپی ایران
برای کسب اطلاعات بیشتر و یا سوالی در زمینه این اسلاید میتوانید به آدرس زیر مراجعه کنید.
http://goo.gl/C9pYi8
ارائه «استفاده از شبکه عصبی مصنوعی» در همایش کدرکانف - مرداد ۱۳۹۵
در این ارائه ابتدا در زمینه یادگیری ماشین توضیحاتی ارائه داده شد و در ادامه راجعبه شیوه کارکرد الگوریتم صحبت شد. در این ارائه سعی شد بدون توجه به زبان برنامهنویسی خاص تنها مقدمات استفاده از این الگوریتم شرح داده شود
در صورت علاقه به این مبحث میتوانید مقاله منتشر شده در همایش را از آدرس زیر دریافت کنید.
(آدرس به زودی معرفی میشود)
A talk I gave at WordCamp Sofa 2016 on measuring and optimizing memory usage, dealing with memory related errors, as well as monitoring server memory health.
Linux memory consumption - Why memory utilities show a little amount of free RAM? How does Linux kernel utilizes free RAM? What is the real amount of free RAM in the system?
Developing High Performance and Scalable ColdFusion Applications Using Terrac...Shailendra Prasad
1. How to scale – options (pros and cons)
2. Caching basics (various options available)
3. Recent updates of Open source Ehcache project.
4. Scaling your existing application with Ehcache, Terracotta OSS
5. Advance caching techniques for scaling using Terracotta BigMemory
6. Customer use cases where caching was mission critical
Let's look at ways how to make PHP applications remember what your user did on the last web page.
The first half will be about the classic PHP sessions, what the SessionHandlerInterface is about and why all of it's methods are important for a successful alternative implementation.
The second half will explore alternatives to the problems created using PHP sessions, including alternatives to sessions: Splitting the problem on the server or moving the data to the client.
Built-in query caching for all PHP MySQL extensions/APIsUlf Wendel
Query caching boosts the performance of PHP MySQL applications. Caching can be done on the database server or at the web clients. A new mysqlnd plugin adds query caching to all PHP MySQL extension: written in C, immediately usable with any PHP application because of no API changes, supports Memcache, APC, SQLite and main memory storage, integrates itself smoothless into existing PHP deployment infrastructure, helps you to scale by client, ... Enjoy!
Caching and tuning fun for high scalabilityWim Godden
Caching has been a 'hot' topic for a few years. But caching takes more than merely taking data and putting it in a cache : the right caching techniques can improve performance and reduce load significantly. But we'll also look at some major pitfalls, showing that caching the wrong way can bring down your site.
If you're looking for a clear explanation about various caching techniques and tools like Memcached, Nginx and Varnish, as well as ways to deploy them in an efficient way, this talk is for you.
ECECS 472572 Final Exam ProjectRemember to check the errata EvonCanales257
ECE/CS 472/572 Final Exam Project
Remember to check the errata section (at the very bottom of the page) for updates.
Your submission should be comprised of two items: a .pdf file containing your written report and a .tar file containing a directory structure with your C or C++ source code. Your grade will be reduced if you do not follow the submission instructions.
All written reports (for both 472 and 572 students) must be composed in MS Word, LaTeX, or some other word processor and submitted as a PDF file.
Please take the time to read this entire document. If you have questions there is a high likelihood that another section of the document provides answers.
Introduction
In this final project you will implement a cache simulator. Your simulator will be configurable and will be able to handle caches with varying capacities, block sizes, levels of associativity, replacement policies, and write policies. The simulator will operate on trace files that indicate memory access properties. All input files to your simulator will follow a specific structure so that you can parse the contents and use the information to set the properties of your simulator.
After execution is finished, your simulator will generate an output file containing information on the number of cache misses, hits, and miss evictions (i.e. the number of block replacements). In addition, the file will also record the total number of (simulated) clock cycles used during the situation. Lastly, the file will indicate how many read and write operations were requested by the CPU.
It is important to note that your simulator is required to make several significant assumptions for the sake of simplicity.
1. You do not have to simulate the actual data contents. We simply pretend that we copied data from main memory and keep track of the hypothetical time that would have elapsed.
2. Accessing a sub-portion of a cache block takes the exact same time as it would require to access the entire block. Imagine that you are working with a cache that uses a 32 byte block size and has an access time of 15 clock cycles. Reading a 32 byte block from this cache will require 15 clock cycles. However, the same amount of time is required to read 1 byte from the cache.
3. In this project assume that main memory RAM is always accessed in units of 8 bytes (i.e. 64 bits at a time).
When accessing main memory, it's expensive to access the first unit. However, DDR memory typically includes buffering which means that the RAM can provide access to the successive memory (in 8 byte chunks) with minimal overhead. In this project we assume an overhead of 1 additional clock cycle per contiguous unit.
For example, suppose that it costs 255 clock cycles to access the first unit from main memory. Based on our assumption, it would only cost 257 clock cycles to access 24 bytes of memory.
4. Assume that all caches utilize a "fetch-on-write" scheme if a miss occurs on a Store operation. This means that you must always fetch ...
ECECS 472572 Final Exam ProjectRemember to check the errat.docxtidwellveronique
ECE/CS 472/572 Final Exam Project
Remember to check the errata section (at the very bottom of the page) for updates.
Your submission should be comprised of two items:
a
.pdf
file containing your written report and a
.tar
file containing a directory structure with your C or C++ source code. Your grade will be reduced if you do not follow the submission instructions.
All written reports (for both 472 and 572 students) must be composed in MS Word, LaTeX, or some other word processor and submitted as a PDF file.
Please take the time to read this entire document. If you have questions there is a high likelihood that another section of the document provides answers.
Introduction
In this final project you will implement a cache simulator. Your simulator will be configurable and will be able to handle caches with varying capacities, block sizes, levels of associativity, replacement policies, and write policies. The simulator will operate on trace files that indicate memory access properties. All input files to your simulator will follow a specific structure so that you can parse the contents and use the information to set the properties of your simulator.
After execution is finished, your simulator will generate an output file containing information on the number of cache misses, hits, and miss evictions (i.e. the number of block replacements). In addition, the file will also record the total number of (simulated) clock cycles used during the situation. Lastly, the file will indicate how many read and write operations were requested by the CPU.
It is important to note that your simulator is required to make several significant assumptions for the sake of simplicity.
1. You do not have to simulate the actual data contents. We simply pretend that we copied data from main memory and keep track of the hypothetical time that would have elapsed.
2. Accessing a sub-portion of a cache block takes the exact same time as it would require to access the entire block. Imagine that you are working with a cache that uses a 32 byte block size and has an access time of 15 clock cycles. Reading a 32 byte block from this cache will require 15 clock cycles. However, the same amount of time is required to read 1 byte from the cache.
3. In this project assume that main memory RAM is always accessed in units of 8 bytes (i.e. 64 bits at a time).
When accessing main memory, it's expensive to access the first unit. However, DDR memory typically includes buffering which means that the RAM can provide access to the successive memory (in 8 byte chunks) with minimal overhead. In this project we assume an
overhead of 1 additional clock cycle per contiguous unit
.
For example, suppose that it costs 255 clock cycles to access the first unit from main memory. Based on our assumption, it would only cost 257 clock cycles to access 24 bytes of memory.
4. Assume that all caches utilize a "fetch-on-write" scheme if a miss occurs on a Store operation. This means that .
ECECS 472572 Final Exam ProjectRemember to check the err.docxtidwellveronique
ECE/CS 472/572 Final Exam Project
Remember to check the errata section (at the very bottom of the page) for updates.
Your submission should be comprised of two items:
a
.pdf
file containing your written report and a
.tar
file containing a directory structure with your C or C++ source code. Your grade will be reduced if you do not follow the submission instructions.
All written reports (for both 472 and 572 students) must be composed in MS Word, LaTeX, or some other word processor and submitted as a PDF file.
Please take the time to read this entire document. If you have questions there is a high likelihood that another section of the document provides answers.
Introduction
In this final project you will implement a cache simulator. Your simulator will be configurable and will be able to handle caches with varying capacities, block sizes, levels of associativity, replacement policies, and write policies. The simulator will operate on trace files that indicate memory access properties. All input files to your simulator will follow a specific structure so that you can parse the contents and use the information to set the properties of your simulator.
After execution is finished, your simulator will generate an output file containing information on the number of cache misses, hits, and miss evictions (i.e. the number of block replacements). In addition, the file will also record the total number of (simulated) clock cycles used during the situation. Lastly, the file will indicate how many read and write operations were requested by the CPU.
It is important to note that your simulator is required to make several significant assumptions for the sake of simplicity.
1. You do not have to simulate the actual data contents. We simply pretend that we copied data from main memory and keep track of the hypothetical time that would have elapsed.
2. Accessing a sub-portion of a cache block takes the exact same time as it would require to access the entire block. Imagine that you are working with a cache that uses a 32 byte block size and has an access time of 15 clock cycles. Reading a 32 byte block from this cache will require 15 clock cycles. However, the same amount of time is required to read 1 byte from the cache.
3. In this project assume that main memory RAM is always accessed in units of 8 bytes (i.e. 64 bits at a time).
When accessing main memory, it's expensive to access the first unit. However, DDR memory typically includes buffering which means that the RAM can provide access to the successive memory (in 8 byte chunks) with minimal overhead. In this project we assume an
overhead of 1 additional clock cycle per contiguous unit
.
For example, suppose that it costs 255 clock cycles to access the first unit from main memory. Based on our assumption, it would only cost 257 clock cycles to access 24 bytes of memory.
4. Assume that all caches utilize a "fetch-on-write" scheme if a miss occurs on a Store operation. This means that.
Today's high-traffic web sites must implement performance-boosting measures that reduce data processing and reduce load on the database, while increasing the speed of content delivery. One such method is the use of a cache to temporarily store whole pages, database recordsets, large objects, and sessions. While many caching mechanisms exist, memcached provides one of the fastest and easiest-to-use caching servers. Coupling memcached with the alternative PHP cache (APC) can greatly improve performance by reducing data processing time. In this talk, Ben Ramsey covers memcached and the pecl/memcached and pecl/apc extensions for PHP, exploring caching strategies, a variety of configuration options to fine-tune your caching solution, and discusses when it may be appropriate to use memcached vs. APC to cache objects or data.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
2. Hello everybody
Julien PAULI
Programming with PHP since early 2000s
Programming in C
PHP Internals programmer/reviewer
PHP 5.5 & 5.6 Release Manager
@julienpauli
Tech blog at jpauli.github.io
jpauli@php.net
3. What about you ?
Got some Unix/Linux understandings ?
Have already experienced C programming ?
Have already experienced PHP programming ?
4. What we'll cover together
Memory , what's that ?
bytes, stack, heap, etc.
Measuring a process memory consumption
memory image map analysis
Understanding PHP memory consumption
Zend Memory Manager coming
Measuring PHP memory consumption
from PHP land or from system land
7. Memory in a user process
The Virtual Memory image is divided in segments
text
data
heap
stack
8. Memory usage can grow
Stack will grow as functions will get called
And will narrow as the calls stop and return
Heap will grow as the programmer will decide
Using dynamic allocation functions (malloc, mmap)
Programmer has to free memory by hand
If not : memory leak
10. Linux memory monitoring
'top' or /proc FS
> cat /proc/28754/status
VmPeak: 20452 kB
VmSize: 20324 kB
VmLck: 0 kB
VmPin: 0 kB
VmHWM: 316 kB
VmRSS: 316 kB
VmData: 16440 kB
VmStk: 136 kB
VmExe: 4 kB
VmLib: 1664 kB
VmPTE: 28 kB
VmSwap: 0 kB
Size of the VM map (out of total mem)
Resident Set Size : Size actually in PM
Size of the data segment in VM
Size of the stack segment in VM
Size of the text segment in VM
pid
11. Going even deeper
Let's show the detailed process memory map :
> cat /proc/28754/smaps
shared segment
private mem
shared mem
13. PHP, just a process
PHP is just a process like any other
You then can monitor its memory usage by asking
the OS
<?php
passthru(sprintf('cat /proc/%d/status', getmypid()));
<?php
function heap() {
return shell_exec(sprintf('grep "VmRSS:" /proc/%d/status', getmypid()));
}
15. The PHP model
One same process may treat many requests
If the process leaks memory, you'll suffer from that
Request n+1 must know nothing about request n
Need to "flush" the request-allocated memory
Need to track request-bound memory claims
ZendMM is the layer that does the job
Share-nothing architecture : by design.
17. Why a custom layer ?
ZendMM
Allows monitoring of request-bound heap usage by
basically counting malloc/free calls
Allows the PHP user to limit the heap mem usage
Allows caching of alloced blocks to prevent memory
fragmentation and syscalls
Allows preallocating blocks of well-known-sizes for
PHP internal structures to fit-in in an aligned way
Ease memory leaks debugging in core and exts
18. ZendMM guards and leak tracker
Only works in debug mode PHP
report_memleaks=1 in php.ini
Does NOT replace valgrind
19. Zend MM test script
<?php
ini_set('memory_limit', -1); /* unlimited ZendMM heap */
function heap() {
return shell_exec(sprintf('grep "VmRSS:" /proc/%d/status', getmypid()));
}
echo heap();
$a = range(1, 1024*1024); /* Stress memory by allocating */
echo heap();
unset($a); /* Stress memory by freeing */
echo heap();
20. Zend MM launch test
> time USE_ZEND_ALLOC=1 php zendmm.php
VmRSS: 9640 kB
VmRSS: 159296 kB
VmRSS: 10068 kB
real 0m0.237s
user 0m0.148s
sys 0m0.080s
> time USE_ZEND_ALLOC=0 php zendmm.php
VmRSS: 9608 kB
VmRSS: 148988 kB
VmRSS: 140804 kB
real 0m0.288s
user 0m0.176s
sys 0m0.108s
21. Valgrind tests for Symfony2 command
app/console runs lots of PHP code under SF2
>USE_ZEND_ALLOC=1 valgrind php app/console debug:container
total heap usage: 84,000 allocs, 84,000 frees, 25,966,154 bytes allocated
>USE_ZEND_ALLOC=0 valgrind php app/console debug:container
total heap usage: 813,570 allocs, 813,570 frees, 74,579,732 bytes allocated
23. ZendMM benefits
Better memory management
More memory efficient
Far less malloc/free calls
Less context switches, less Kernel stress
Less CPU usage
Less heap fragmentation / compaction
A PHP ~10% faster with ZendMM enabled
Really depends on use-case
24. Memory manager internals
Layer on top of the heap
Will allocate memory from the heap by chunks of
customizable size (segments)
Will use a customizable low level heap (malloc /
mmap)
25. A quick word on ZendMM internals
ZEND_MM_SEG_SIZE env variable to customize
segment size
Must be power-of-two aligned
Default value is 256Kb
26. ZendMM in PHP user land
memory_limit (INI setting)
memory_get_usage(true)
Returns the size of all the allocated segments
memory_get_usage()
Returns the occupied size in all the allocated
segments
memory_get_[peak]_usage([real])
Returns the max memory that has been
allocated/used. Could have been freed meantime
30. memory_get_usage() ?
memory_get_usage() tells you how much your
allocated blocs consume
They usually don't fill their segment entirely
Thus memory_get_usage(true) shows more
This doesn't count stack
This does only count request-bound memory
This doesn't count linked libraries present in the
process memory map
This doesn't show non-request-bound memory
34. Recommendations / statements
Understand memory_get_usage()
It only shows request-bound allocations, not
persistent allocations (that reside through requests)
PHP extensions may allocate persistent memory
Do NOT activate extensions you will not use
Libraries used by PHP may also allocate persistent
memory
Use your OS to monitor your process memory
accurately
36. Master your PHP mem usage
In PHP land ...
all variable types consume memory
every script asked for compilation will eat memory
This memory will be allocated using ZendMM
The memory for parsed script is freed when the
request ends
The memory for user variable is freed when the
data is not used any more
And here comes the challenge
When isn't the data needed any more ??
37. Compilation eats memory
Compiling a script eats request-bound memory
If you compile a class, that eats lots of memory
You'd better use that class at runtime
Use an autoloader to be sure
<?php
$mem = memory_get_usage();
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../src/Symfony/Component/DependencyInjection/ContainerBuilder.php'
echo memory_get_usage() - $mem . "n";
php app/bar.php
246,692
39. PHP Variables
What eats memory is what is stored into the zval,
not really the zval itself :
A huge string
Tip : a file_get_contents('huge-file') is a huge string
A complex array or object
Resources don't really consume mem in zval
<?php
/* This consumes sizeof(zval) + 1024 bytes */
$a = str_repeat('a', 1024);
40. PHP Variables
What you want to avoid is have PHP duplicate the
zval
But PHP is kind about that
What you want to happen in PHP freeing the
memory ASAP
Should you know when PHP duplicates or frees zval
, that's the most important !
41. zvals and refcount
PHP simply counts how many symbols (PHP
vars) point to a zval
This is called the refcount
<?php
$a = "foo";
$b = $a;
42. zvals and refcount
PHP uses a CopyOnWrite (COW) system for
zvals
Memory is saved
Memory gets allocated only on changes
<?php
$a = "foo";
$b = $a;
$a = 17;
43. zvals and refcount
PHP frees memory for a zval
when its refcount reaches 0
Yes, unset() just refcount-- ,
that's all
<?php
$a = "foo";
$b = $a;
$c = $b;
$b = "bar";
unset($a);
44. No references needed
You see how smart PHP is with memory ?
It's been designed with that in mind
No references needed to hint PHP !
Don't try to hint PHP with references
References can lead to adverse effects
Force PHP to copy a zval
Prevents PHP from freeing memory of a zval
&
45. Tracking refcount
xdebug_debug_zval()
symfony_zval_info()
namespace Foo;
class A
{
public $var = 'varA';
}
$a = new A();
xdebug_debug_zval('a');
a: (refcount=1, is_ref=0)=class FooA { public $var =
(refcount=2, is_ref=0)='varA'; }
46. Tracking refcount
namespace Foo;
class C
{
public $b;
public function __construct(B $b) {
$this->b = $b;
}
}
$c = new C($b = new B);
xdebug_debug_zval('c');
c: (refcount=1, is_ref=0)=class FooC { public $b = (refcount=2, is_ref=0)=class FooB { } }
namespace Foo;
class B
{
}
unset($b);
xdebug_debug_zval('c');
c: (refcount=1, is_ref=0)=class FooC { }
c: (refcount=1, is_ref=0)=class FooC { public $b = (refcount=1, is_ref=0)=class FooB { } }
unset($c->b);
xdebug_debug_zval('c');
47. Garbage collector ?
As of PHP5.3 , a garbage collector exists
Used to free circular references
And that's all !
PHP already frees itself your vars as their
refcount reaches 0
And it's always been like that
48. Circular references
$a = new A;
$b = new B
(object) 'A'
refcount = 1
$a (object) 'B'
refcount = 1
$b
50. Circular references
Objects are still in memory but no more PHP var
point to them
We can call that a "PHP Userland memory leak"
unset($a, $b);
(object) 'A'
refcount = 1
$b->a (object) 'B'
refcount = 1
$a->b
53. PHP references main line
Using references (&) in PHP can really fool you
They usually force the engine to duplicate memory
containers
Which is bad for performance
Especially when the var container is huge
54. References mismatch
<?php
function foo($data)
{
echo "in function : " . memory_get_usage() . "n";
}
echo "Initial memory : " . memory_get_usage() . "n";
$r = range(1, 1024);
echo "Array created : " . memory_get_usage() . "n";
foo($r);
echo "End of function " . memory_get_usage() . "n";
Initial memory : 227.136
Array created : 374.912
in function : 374.944
End of function 374.944
55. References mismatch
<?php
function foo($data)
{
echo "in function : " . memory_get_usage() . "n";
}
echo "Initial memory : " . memory_get_usage() . "n";
$r = range(1, 1024);
$r2 = &$r;
echo "Array created : " . memory_get_usage() . "n";
foo($r);
echo "End of function " . memory_get_usage() . "n";
Initial memory : 227.208
Array created : 375.096
in function : 473.584
End of function 375.128
56. When does the engine separate ?
In any mismatch case :
zval passed to function arginfo decl. zval received in function separated by engine?
is_ref=0
refcount = 1
pass_by_ref=0 is_ref=0
refcount = 2
NO
is_ref=1
refcount > 1
pass_by_ref=0 is_ref=1
refcount =1
YES
is_ref=0
refcount > 1
pass_by_ref=0 is_ref=0
refcount > 1 ++
NO
is_ref=0
refcount = 1
pass_by_ref=1 is_ref=1
refcount = 2
YES
is_ref=1
refcount > 1
pass_by_ref=1 is_ref=1
refcount > 1 ++
NO
is_ref=0
refcount > 1
pass_by_ref=1 is_ref=1
refcount = 2
YES
57. Symfony_debug to notice mismatches
https://github.com/symfony/debug
function bar($var) { }
$a = "foo";
$b = &$a;
bar($a);
Notice: Separating zval for call to function 'bar' in /tmp/memory.php on line 20
59. Foreach separation behavior
It happens sometimes foreach() duplicates your
variable for iteration
This will eat performances in case of big or
complex arrays being iterated
There is nothing special to say about objects
implementing Traversable
The behavior is then just yours
60. foreach iterating array #1
If the variable has a refcount of 1, no duplication is
performed by foreach()
$a = range(1,1024);
echo memory_get_usage() . "n" ;
foreach ($a as $v) {
if ($v == 1) {
echo memory_get_usage() . "n" ;
}
}
echo memory_get_usage() . "n" ;
373936
374056
374056
61. foreach iterating array #2
If the variable has a refcount >1, foreach() will
duplicate it fully for iteration
$a = range(1,1024);
$b = $a;
echo memory_get_usage() . "n" ;
foreach ($a as $v) {
if ($v == 1) {
echo memory_get_usage() . "n" ;
}
}
echo memory_get_usage() . "n" ;
373936
472512
374056
62. foreach iterating array #3
If the variable is a reference, foreach() will work
onto that array and won't perform duplication
$a = range(1,1024);
$b = &$a;
echo memory_get_usage() . "n" ;
foreach ($a as $v) {
if ($v == 1) {
echo memory_get_usage() . "n" ;
}
}
echo memory_get_usage() . "n" ;
373936
374056
374056
63. Monitoring memory usage
Not much tools exist (for PHP)
memory_get_usage()
OS' help (/proc , pmap , etc...)
Valgrind with massif tool
PHP Extensions
Xdebug
memprof
memtrack
64. Quick intro to memprof
https://github.com/arnaud-lb/php-memory-profiler
$b = range(1, 1024 * 1024); /* a lot of memory */
$b[] = foo();
loader('/Zend/Date.php'); /* a lot of PHP source code */
memprof_dump_callgrind(fopen('/tmp/trace.out', 'w'));