Home Database Redis What are the techniques for memory allocation and usage statistics of Redis?

What are the techniques for memory allocation and usage statistics of Redis?

May 27, 2023 pm 07:44 PM
redis

Specifically:

If Google’s TC_MALLOC library exists in the system, use the tc_malloc family of functions instead of the original malloc family of functions.

If the current system is a Mac system, use the memory allocation function.

In other cases, an additional fixed-length field is allocated at the beginning of each allocated space to record the allocated space size.

The source codes are in config.h and zmalloc.c respectively:

/* config.h */

#if defined(USE_TCMALLOC)

#include

 #if TC_VERSION_MAJOR >= 1 && TC_VERSION_MINOR >= 6

 #define HAVE_MALLOC_SIZE 1

 #define redis_malloc_size(p) tc_malloc_size(p)

  #endif

  #elif defined(__APPLE__)

  #include

  #define HAVE_MALLOC_SIZE 1

  #define redis_malloc_size(p) malloc_size(p )

 #endif

 /* zmalloc.c */

 #ifdef HAVE_MALLOC_SIZE

 #define PREFIX_SIZE (0)

 # else

 #if defined(__sun)

 #define PREFIX_SIZE (sizeof(long long))

 #else

 #define PREFIX_SIZE (sizeof(size_t ))

 #endif

 #endif

Because tc_malloc and the malloc function family under the Mac platform provide functions for calculating the size of allocated space (tc_malloc_size and malloc_size respectively) , so there is no need to allocate a separate space to record the size. For Linux and Sun platforms, the size of the allocated space must be recorded. For linux, use sizeof(size_t) fixed-length field record; for sun os, use sizeof(long long) fixed-length field record. That is the PREFIX_SIZE macro in the source code above.

Re-express this sentence: The purpose of this record is to calculate how much memory is occupied by the current process. In zmalloc.c, there is such a static variable:

static size_t used_memory = 0;

It records the total amount of memory currently occupied by the process. Whenever memory is allocated or released, this variable must be updated. Because when allocating memory, you can clearly know how much memory to allocate. But when releasing memory, (for platforms that do not provide the malloc_size function) you cannot know how much space is released just by pointing to the pointer to the memory to be released. In this case, the fixed-length field specified by PREFIX_SIZE comes into play, and the size of the space can be obtained from the information recorded in it. The zmalloc function is as follows (removing irrelevant code):

void *zmalloc(size_t size) {

void *ptr = malloc(size PREFIX_SIZE);

if (!ptr) zmalloc_oom(size);

 *((size_t*)ptr) = size;

 update_zmalloc_stat_alloc(size PREFIX_SIZE,size);

 return (char*)ptr PREFIX_SIZE;

 . When running on a Mac system or using tc_malloc, the value of PREFIX_SIZE is zero. Next, the first size_t bytes of the memory block pointed to by the pointer ptr will be used to record the allocated size of the memory block. The last thing returned is the pointer beyond the record area. The zfree function is similar (removing irrelevant code):

void zfree(void *ptr) {

void *realptr;

size_t oldsize;

if ( ptr == NULL) return;

realptr = (char*)ptr-PREFIX_SIZE;

oldsize = *((size_t*)realptr);

update_zmalloc_stat_free(oldsize PREFIX_SIZE );

free(realptr);

#endif

}

First move the pointer forward PREFIX_SIZE, and then take out the space saved when allocating space length. Finally, free the entire space.

The two macros update_zmalloc_stat_alloc(__n,__size) and update_zmalloc_stat_free(__n) are responsible for updating the used_memory variable when allocating or releasing memory. Defining it as a macro is mainly due to efficiency considerations. Restore it to a function, as follows:

void update_zmalloc_stat_alloc(__n,__size)

 {

 do {

 size_t _n = (__n );

 size_t _stat_slot = (__size < ZMALLOC_MAX_ALLOC_STAT) ? __size : ZMALLOC_MAX_ALLOC_STAT; ​if (_n&(sizeof(long)-1)) _n = sizeof(long)-(_n&(sizeof(long)-1)); ​if (zmalloc_thread_safe) { ​pthread_mutex_lock(&used_memory_mutex); ​used_memory = _n; ​zmalloc_allocations[_stat_slot]; ​pthread_mutex_unlock(&used_memory_mutex); } else { ​used_memory = _n; ​zmalloc_allocations[_stat_slot]; } } while(0) } void update_zmalloc_stat_free(__n) { do { size_t _n = (__n); ​if (_n&(sizeof(long)-1)) _n = sizeof(long)-(_n&(sizeof(long)-1)); ​if (zmalloc_thread_safe) { ​pthread_mutex_lock(&used_memory_mutex); ​used_memory -= _n; ​pthread_mutex_unlock(&used_memory_mutex); } else { ​used_memory -= _n; } } while(0) } In addition to updating the used_memory variable in the code, there are several other things to pay attention to: First, the low-order bits of _n are rounded up, and finally _n becomes a multiple of sizeof(long). For example, for a 32-bit system, sizeof(long) == 100 (binary). After _n is rounded up, the two low-order bits become is 0. If there are multiple threads in the process, locks must be locked when updating variables. There is another statistic to be updated in the zmalloc function: zmalloc_allocations[]. In zmalloc.c, zmalloc_allocations is defined as follows: size_t zmalloc_allocations[ZMALLOC_MAX_ALLOC_STAT 1]; Its function is to count the number of requests for different sizes of space when the program allocates memory. The statistical space ranges from 1 byte to 256 bytes, and the space larger than 256 bytes is counted as 256. Statistical results are returned by calling the zmalloc_allocations_for_size function: size_t zmalloc_allocations_for_size(size_t size) { if (size > ZMALLOC_MAX_ALLOC_STAT) return 0;

Return zmalloc_allocations[size];

}

Another memory usage statistics is returned by calling the zmalloc_used_memory function:

Size_t zmalloc_used_memory(void) {

size_t um;

if (zmalloc_thread_safe) pthread_mutex_lock(&used_memory_mutex);

um = used_memory;

 if (zmalloc_thread_safe) pthread_mutex_unlock(&used_memory_mutex);

return um;

 }

In addition, zmalloc.c also implements the zmalloc_get_rss function for different systems. In linux In the system, system statistics of memory usage are obtained by reading the /proc/$pid/stat file.

The above is the detailed content of What are the techniques for memory allocation and usage statistics of Redis?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

See all articles