Sis*_*utl 37 c# performance cpu-usage performance-testing wait
对于我正在做的一些测试,我需要一个C#函数,大约需要10秒才能执行.它将从ASPX页面调用,但我需要在服务器上占用CPU时间的功能,而不是渲染时间.对Northwinds数据库的慢速查询会起作用,或者计算速度很慢.有任何想法吗?
Par*_*ram 53
尝试计算第n个素数以模拟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);
}
Run Code Online (Sandbox Code Playgroud)
需要多长时间取决于系统的硬件配置.
因此尝试输入为1000然后增加输入值或减少它.
此功能将模拟CPU密集型工作.
Mot*_*tti 17
Arguably the simplest such function is this:
public void Slow()
{
var end = DateTime.Now + TimeSpan.FromSeconds(10);
while (DateTime.Now < end)
/*nothing here */ ;
}
Run Code Online (Sandbox Code Playgroud)
Moh*_*eid 11
You can use a 'while' loop to make the CPU busy.
void CpuIntensive()
{
var startDt = DateTime.Now;
while (true)
{
if ((DateTime.Now - startDt).TotalSeconds >= 10)
break;
}
}
Run Code Online (Sandbox Code Playgroud)
此方法将在while循环中保持10秒.此外,如果在多个线程中运行此方法,则可以使所有CPU核心忙碌.
为了最大化多个核心,我调整了@ Motti的答案,得到了以下结果:
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.
Run Code Online (Sandbox Code Playgroud)
This is CPU intensive on a single thread/CPU, and lasts 10 seconds.
var endTime = DateTime.Now.AddSeconds(10);
while(true) {
if (DateTime.Now >= endTime)
break;
}
Run Code Online (Sandbox Code Playgroud)
As a side note, you should not normally do this.
| 归档时间: |
|
| 查看次数: |
11839 次 |
| 最近记录: |