Necesito una función lenta de C#


Para algunas pruebas que estoy haciendo necesito una función de C# que tarda alrededor de 10 segundos en ejecutarse. Se llamará desde una página ASPX, pero necesito que la función consuma el tiempo de CPU en el servidor, no el tiempo de renderizado. Una consulta lenta en la base de datos de Northwinds funcionaría, o algunos cálculos muy lentos. Alguna idea?

Author: Parag Meshram, 2012-10-21

6 answers

Trate de calcular el n-ésimo número primo para simular el trabajo intensivo de la CPU -

public void Slow()
{
    long nthPrime = FindPrimeNumber(1000); //set higher value for more time
}

public long FindPrimeNumber(int n)
{
    int count=0;
    long a = 2;
    while(count<n)
    {
        long b = 2;
        int prime = 1;// to check if found a prime
        while(b * b <= a)
        {
            if(a % b == 0)
            {
                prime = 0;
                break;
            }
            b++;
        }
        if(prime > 0)
        {
            count++;
        }
        a++;
    }
    return (--a);
}

El tiempo que tomará dependerá de la configuración de hardware del sistema.

Así que intente con la entrada como 1000 y luego aumente el valor de entrada o disminuya.

Esta función simulará el trabajo intensivo de la CPU.

 44
Author: Parag Meshram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-18 11:20:28

Podría decirse que la función más simple es esta:

public void Slow()
{
    var end = DateTime.Now + TimeSpan.FromSeconds(10);
    while (DateTime.Now < end)
           /*nothing here */ ;
}
 16
Author: Motti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-21 20:01:22

Puede usar un bucle 'while' para que la CPU esté ocupada.

    void CpuIntensive()
    {
        var startDt = DateTime.Now;

        while (true)
        {
            if ((DateTime.Now - startDt).TotalSeconds >= 10)
                break;
        }
    }

Este método permanecerá en el bucle while durante 10 segundos. Además, si ejecuta este método en varios subprocesos, puede hacer que todos los núcleos de la CPU estén ocupados.

 10
Author: Mohammad Banisaeid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-21 20:03:04

Esto es intensivo de CPU en un solo subproceso/CPU, y dura 10 segundos.

var endTime = DateTime.Now.AddSeconds(10);

while(true) {
   if (DateTime.Now >= endTime) 
      break;
}

Como nota al margen, normalmente no deberías hacer esto.

 7
Author: Sklivvz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-21 20:02:38

Para maximizar múltiples núcleos ajusté un poco la respuesta de @Motti, y obtuve lo siguiente:

Enumerable
  .Range(1, Environment.ProcessorCount) // replace with lesser number if 100% usage is not what you are after.
  .AsParallel()
  .Select(i => {
    var end = DateTime.Now + TimeSpan.FromSeconds(10);
    while (DateTime.Now < end)
      /*nothing here */ ;
    return i;
  })
  .ToList(); // ToList makes the query execute.
 5
Author: Johny Skovdal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-17 21:16:55

Solo use
Thread.Sleep(number of milliseconds here);
Tendrás que añadir using System.Threading;

 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-11 20:46:29