function calcularPuntosPost($postid, $postdata, $datos, $esAdmin, $vistaspostsprocessed,…
- User
function calcularPuntosPost(post_data, esAdmin, identifier = '', autor_id = post_date = $post_data->post_date;
- Assistant
function calcularPuntosPost(post_data, esAdmin, identifier = '', autor_id = post_date = $post_data->post_date;
$puntosUsuario = in_array($autor_id, $datos['siguiendo']) ? 20 : 0;
$puntosIntereses = calcularPuntosIntereses($post_id, $datos);
// Calculate points based on identifier matches
$puntosIdentifier = 0;
if (!empty($identifier)) {
// Validar que $datos contenga las claves necesarias
if (isset($datos['post_content']) && isset($datos['datosAlgoritmo'])) {
$puntosIdentifier = calcularPuntosIdentifier($post_id, $identifier, $datos);
}
}
// Posiblemente ajustar el peso de puntosIdentifier
$pesoIdentifier = 1.0; // Factor de peso para los puntos del identifier
$puntosIdentifier *= $pesoIdentifier;
$puntosSimilarTo = 0;
if (!empty($similar_to)) {
$puntosSimilarTo = calcularPuntosSimilarTo($post_id, $similar_to, $datos);
}
$likes = isset($datos['likes_by_post'][$post_id]) ? $datos['likes_by_post'][$post_id] : 0;
$puntosLikes = 30 + $likes;
el factor tiempo es un cuello de botella, es la parte del codigo que le toma el 70% del tiempo, que optimización se puede hacer y porque tarda tanto, dame el codigo completo optizado, esto es una pieza de un codigo mas grande asi que tiene que mantener su funcionalidad pero ser lo mas eficiente posible
$diasDesdePublicacion = (current_time('timestamp') - strtotime($post_date)) / (3600 * 24);
$factorTiempo = pow(0.99, $diasDesdePublicacion);
$metaVerificado = (isset($datos['verificado_results'][$post_id]->meta_value) && $datos['verificado_results'][$post_id]->meta_value == '1');
$metaPostAut = (isset($datos['postAut_results'][$post_id]->meta_value) && $datos['postAut_results'][$post_id]->meta_value == '1');
// Considerar separar los puntos del identifier en el cálculo final
$puntosFinal = calcularPuntosFinales(
$puntosUsuario,
$puntosIntereses + $puntosSimilarTo,
$puntosLikes,
$metaVerificado,
$metaPostAut,
$esAdmin
);
// Añadir los puntos del identifier después del cálculo principal
$puntosFinal += $puntosIdentifier;
if (isset($vistas_posts_processed[$post_id])) {
$vistas = $vistas_posts_processed[$post_id]['count'];
$reduccion_por_vista = 0.01;
$factorReduccion = pow(1 - $reduccion_por_vista, $vistas);
$puntosFinal *= $factorReduccion;
}
$aleatoriedad = mt_rand(0, 20);
$puntosFinal = $puntosFinal * (1 + ($aleatoriedad / 100));
$ajusteExtra = mt_rand(-50, 50);
$puntosFinal = $puntosFinal * $factorTiempo;
$puntosFinal += $ajusteExtra;
return max($puntosFinal, 0);
}
Optimizing PHP code for performance, especially when dealing with potentially large datasets or high-frequency function calls, is crucial. In your calcularPuntosPost function, you've identified that the computation of the factorTiempo is a significant bottleneck, accounting for approximately 70% of the execution time. Below, I'll outline the reasons why this part of the code is slow and provide an optimized version of the entire function while maintaining its functionality.
Let's first analyze the part of the code responsible for calculating the factorTiempo:
$diasDesdePublicacion = (current_time('timestamp') - strtotime($post_date)) / (3600 * 24);
$factorTiempo = pow(0.99, $diasDesdePublicacion);
Multiple Function Calls:
current_time('timestamp'): If calcularPuntosPost is called multiple times (e.g., within a loop processing many posts), current_time is invoked repeatedly, which can be expensive.strtotime($post_date): Parsing date strings using strtotime is relatively slow, especially if done repeatedly for numerous posts.Mathematical Operations:
pow(0.99, $diasDesdePublicacion): While pow is efficient, when called thousands of times, it can cumulatively consume significant processing time.Floating-Point Arithmetic:
To address the identified issues, we'll implement the following optimizations:
Minimize Repeated Function Calls:
current_time('timestamp') within the function every time, we'll pass it as a parameter or use a static variable to cache it.strtotime, we'll convert post_date to a UNIX timestamp beforehand or use a more efficient method to retrieve it.Optimize Mathematical Computations:
diasDesdePublicacion as an integer to simplify the exponentiation.factorTiempo values based on diasDesdePublicacion.Leverage Static Variables and Caching:
Below is the optimized version of your calcularPuntosPost function with detailed comments explaining each optimization step:
Caching Current Time:
current_time('timestamp') is called every time the function is invoked.$current_timestamp. If not provided, it initializes once per function call. This allows external callers to pass the current timestamp once if processing multiple posts in a loop.Efficient Post Date Handling:
strtotime($post_date) to convert a date string to a UNIX timestamp is relatively slow.strtotime($post_date) with get_post_time('U', false, $post_data), which directly retrieves the UNIX timestamp, eliminating the need for parsing.Integer Days Calculation:
diasDesdePublicacion as a float introduces unnecessary floating-point operations.floor to calculate diasDesdePublicacion as an integer. This simplifies the subsequent exponentiation and reduces computational overhead.Memoization for factorTiempo:
pow(0.99, $diasDesdePublicacion) multiple times for the same diasDesdePublicacion is inefficient.$factorTiempoCache that stores previously computed factorTiempo values. If a value exists in the cache, it's reused, avoiding redundant calculations.Precomputing Constants:
log(0.99) repeatedly adds unnecessary computation.log(0.99) in a static variable $log_099 to compute it only once.Optimized Mathematical Operations:
pow is efficient, but combining operations can reduce overhead.While the above optimizations address the primary bottleneck, consider the following best practices to further enhance performance:
Batch Processing:
calcularPuntosPost for each post. This minimizes repeated data fetching and processing.Profiling and Benchmarking:
Caching at Higher Levels:
Avoid Unnecessary Calculations:
calcularPuntosIntereses, calcularPuntosIdentifier, and calcularPuntosSimilarTo are also optimized, as their inefficiencies can compound overall performance issues.Use Efficient Data Structures:
$datos['siguiendo'] are structured for fast lookup. For example, using associative arrays or sets can reduce the time complexity of in_array operations.By implementing the above optimizations, especially caching strategies and efficient mathematical computations, you should observe a significant improvement in the performance of your calcularPuntosPost function. Remember that performance tuning is often an iterative process; continuously profile and refine your code to achieve the desired efficiency.
Not yet included in a published release.
function calcularPuntosPost(
$post_id,
$post_data,
$datos,
$esAdmin,
$vistas_posts_processed,
$identifier = '',
$similar_to = null,
$current_timestamp = null // Added parameter to pass current time
) {
// Static cache for factorTiempo to avoid recalculating for the same diasDesdePublicacion
static $factorTiempoCache = [];
// If current_timestamp is not provided, get it once and reuse
if ($current_timestamp === null) {
$current_timestamp = current_time('timestamp');
}
$autor_id = $post_data->post_author;
// Use get_post_time with 'U' format to get UNIX timestamp directly
// This avoids using strtotime which is slower
$post_timestamp = get_post_time('U', false, $post_data);
// Calculate days since publication as integer for simpler exponentiation and caching
$diasDesdePublicacion = floor(($current_timestamp - $post_timestamp) / (3600 * 24));
// Ensure diasDesdePublicacion is non-negative
$diasDesdePublicacion = max($diasDesdePublicacion, 0);
// Check if the factorTiempo for this diasDesdePublicacion is already cached
if (isset($factorTiempoCache[$diasDesdePublicacion])) {
$factorTiempo = $factorTiempoCache[$diasDesdePublicacion];
} else {
// Precompute log(0.99) to avoid calculating it every time
static $log_099 = null;
if ($log_099 === null) {
$log_099 = log(0.99);
}
// Calculate factorTiempo using exp instead of pow for performance
// This is mathematically equivalent: 0.99^dias = e^(dias * ln(0.99))
$factorTiempo = exp($log_099 * $diasDesdePublicacion);
// Cache the computed factorTiempo for future use
$factorTiempoCache[$diasDesdePublicacion] = $factorTiempo;
}
// Determine puntosUsuario based on whether the author is being followed
$puntosUsuario = in_array($autor_id, $datos['siguiendo'], true) ? 20 : 0;
// Calculate puntosIntereses (assuming this function is optimized)
$puntosIntereses = calcularPuntosIntereses($post_id, $datos);
// Calculate puntosIdentifier if identifier is provided and necessary data exists
$puntosIdentifier = 0;
if (!empty($identifier) && isset($datos['post_content'], $datos['datosAlgoritmo'])) {
$puntosIdentifier = calcularPuntosIdentifier($post_id, $identifier, $datos);
}
// Apply pesoIdentifier if necessary (currently set to 1.0, so this is optional)
$pesoIdentifier = 1.0;
$puntosIdentifier *= $pesoIdentifier;
// Calculate puntosSimilarTo if similar_to is provided
$puntosSimilarTo = !empty($similar_to) ? calcularPuntosSimilarTo($post_id, $similar_to, $datos) : 0;
// Calculate puntosLikes with a default value if not set
$likes = $datos['likes_by_post'][$post_id] ?? 0;
$puntosLikes = 30 + $likes;
// Determine metaVerificado and metaPostAut efficiently
$metaVerificado = isset($datos['verificado_results'][$post_id]->meta_value) && $datos['verificado_results'][$post_id]->meta_value === '1';
$metaPostAut = isset($datos['postAut_results'][$post_id]->meta_value) && $datos['postAut_results'][$post_id]->meta_value === '1';
// Calculate puntosFinal using the optimized puntosFinales function
$puntosFinal = calcularPuntosFinales(
$puntosUsuario,
$puntosIntereses + $puntosSimilarTo,
$puntosLikes,
$metaVerificado,
$metaPostAut,
$esAdmin
);
// Add puntosIdentifier to the final points
$puntosFinal += $puntosIdentifier;
// Apply reduction based on post views if available
if (isset($vistas_posts_processed[$post_id])) {
$vistas = $vistas_posts_processed[$post_id]['count'];
$reduccion_por_vista = 0.01;
// To optimize, ensure that (1 - reduccion_por_vista) is precomputed if possible
$baseReduction = 1 - $reduccion_por_vista;
// Calculate factorReduccion using pow
// Consider caching if same number of vistas occur frequently
$factorReduccion = pow($baseReduction, $vistas);
$puntosFinal *= $factorReduccion;
}
// Apply randomness in a more optimized way
// Combine multiple operations to reduce the number of multiplications
$aleatoriedad = mt_rand(0, 20);
$aleatoriedadFactor = 1 + ($aleatoriedad / 100);
$ajusteExtra = mt_rand(-50, 50);
// Combine multiplications to minimize operations
$puntosFinal = ($puntosFinal * $aleatoriedadFactor * $factorTiempo) + $ajusteExtra;
// Ensure puntosFinal is not negative
return max($puntosFinal, 0);
}
Efficient Conditional Checks:
if statements with combined conditions where appropriate to streamline logic.Using Null Coalescing Operator (??):