C# 内存缓存.NET4.0性能测试:惊人的结果
此性能测试错误,或者系统缓存的性能异常?C# 内存缓存.NET4.0性能测试:惊人的结果,c#,performance,validation,.net-4.0,memorycache,C#,Performance,Validation,.net 4.0,Memorycache,此性能测试错误,或者系统缓存的性能异常? 这是我的结果: [13] 交互次数100000:63毫秒 [14] 交互次数100000:139毫秒 [12] 交互次数100000:47毫秒 [15] 交互次数100000:44毫秒 测试结束。 硬件: x86系列6型号23英特尔~2992 Mhz 3.327 MB,5.1.2600 Service Pack 3 using System; using System.Collections.Generic; using System.Runtime.
这是我的结果:
[13] 交互次数100000:63毫秒
[14] 交互次数100000:139毫秒
[12] 交互次数100000:47毫秒
[15] 交互次数100000:44毫秒
测试结束。
硬件: x86系列6型号23英特尔~2992 Mhz 3.327 MB,5.1.2600 Service Pack 3
using System;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Diagnostics;
using System.Threading;
namespace CacheNet40
{
public class CacheTest
{
private ObjectCache cache;
public CacheTest()
{
cache = MemoryCache.Default;
}
public void AddItem(CacheItem item, double span)
{
CacheItemPolicy cp = new CacheItemPolicy();
cp.SlidingExpiration.Add(TimeSpan.FromMinutes(span));
cache.Add(item, cp);
}
public Object GetItem(string key)
{
return cache.Get(key);
}
}
class Program
{
private static CacheTest Cache = new CacheTest();
private static string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
private static int counter = 0;
private static readonly object locker = new object();
static string CreateRandomString(int passwordLength, int idx)
{
char[] chars = new char[passwordLength];
Random rd = new Random((int)DateTime.Now.Ticks + idx);
for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}
private static void CacheAccessTes()
{
int span = 5;
string key;
string data;
int itens = 1000;
int interactions = 100000;
int cont = 0;
int index = 0;
List<string> keys = new List<string>();
lock (locker)
{
counter++;
}
cont = itens;
//populates it with data in the cache
do
{
key = CreateRandomString(127, Thread.CurrentThread.ManagedThreadId + cont);
keys.Add(key);
data = CreateRandomString(156000, Thread.CurrentThread.ManagedThreadId + cont + 1);
CacheItem ci = new CacheItem(key, data);
Cache.AddItem(ci, span);
cont--;
}
while (cont > 0);
cont = interactions;
index = 0;
//test readings
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
do
{
Object ci = Cache.GetItem(keys[index]);
ci = null;
index++;
if (index == itens)
{
index = 0;
}
cont--;
}
while (cont > 0);
stopWatch.Stop();
lock (locker)
{
counter--;
}
string outstring = String.Format("[{0}] number of interactions {1} : {2} milliseconds", Thread.CurrentThread.ManagedThreadId, interactions, stopWatch.ElapsedMilliseconds );
Console.WriteLine(outstring);
}
static void Main(string[] args)
{
for (int threads = 0; threads < 4; threads++)
{
Thread thread = new Thread(new ThreadStart(CacheAccessTes));
thread.Start();
}
Thread.Sleep(1000);
while (true)
{
lock (locker)
{
if (counter == 0) break;
}
Thread.Sleep(100);
}
Console.WriteLine("End of test.");
Console.ReadLine();
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Runtime.Caching;
使用系统诊断;
使用系统线程;
名称空间缓存40
{
公共类缓存测试
{
私有对象缓存;
公共缓存测试()
{
cache=MemoryCache.Default;
}
公共无效附加项(CacheItem,双跨度)
{
CacheItemPolicy cp=新的CacheItemPolicy();
cp.slidengexpiration.Add(TimeSpan.frommins(span));
cache.Add(item,cp);
}
公共对象GetItem(字符串键)
{
返回cache.Get(key);
}
}
班级计划
{
私有静态CacheTest缓存=新建CacheTest();
私有静态字符串allowedChars=“abcdefghjjkmnopqrstuvwxyzabcdefghjklmnopqrstuvwxyzo123456789!@$?”;
专用静态整数计数器=0;
私有静态只读对象锁定器=新对象();
静态字符串CreateRandomString(int passwordLength,int idx)
{
char[]chars=新字符[passwordLength];
随机rd=新随机((int)DateTime.Now.Ticks+idx);
for(int i=0;i0);
cont=相互作用;
指数=0;
//测试读数
秒表秒表=新秒表();
秒表。开始();
做
{
对象ci=Cache.GetItem(键[index]);
ci=null;
索引++;
如果(索引==itens)
{
指数=0;
}
续--;
}
而(续>0);
秒表;
锁(储物柜)
{
计数器--;
}
string outstring=string.Format(“[{0}]交互次数{1}:{2}毫秒”,Thread.CurrentThread.ManagedThreadId,交互,stopWatch.ElapsedMilliseconds);
控制台。写入线(突出);
}
静态void Main(字符串[]参数)
{
对于(int线程=0;线程<4;线程++)
{
线程线程=新线程(新线程开始(缓存访问));
thread.Start();
}
睡眠(1000);
while(true)
{
锁(储物柜)
{
如果(计数器==0)中断;
}
睡眠(100);
}
控制台写入线(“测试结束”);
Console.ReadLine();
}
}
}
看起来不错。虽然低于一秒的计时并不十分可靠;您可能会遇到垃圾收集,您的PC可能会在短时间内执行其他操作,第一次JIT编译等
因此,增加计数。这也会使每个线程的结果更加接近
我上周做的一些测试使其达到每秒800万次(虽然做得不多,但仍然是)单线程。所以,是的,现在个人电脑的速度很快;-) 问题在于秒表类不能在多核机器上使用!(我假设你有一个多核CPU)当一个线程从一个核心移动到另一个核心时,BIOS如何处理这个计数器(即使是一个单线程应用程序也会跳转到另一个核心!) 编辑:
查看--特别是备注部分。 还有一个stackoverflow post-。 结束编辑
我到处寻找衡量应用程序性能的最佳方法,我找到的最可靠的方法是DateTime.UtcNow。获取开始和结束时间,然后计算它们之间的差异。您必须循环足够的代码才能通过低精度,但我遇到的任何其他方法都不能提供更可靠的精度。在我的机器上,每次调用GetItem大约需要40毫秒或400纳秒
我在debugger下跟踪调用,在我的I7机器上,每个GetItem大约有2000条指令。这超出了我的预期。我刚刚在网上搜索了有关内存缓存性能的信息,偶然发现了这个问题。我问自己为什么没有使用一个合适的基准库,所以我最终通过非常懒惰(所有优秀的程序员都应该如此:-)来编写自己的基准,并使用这个不可思议的库来检查它的性能
BenchmarkDotNet=v0.11.5, OS=Windows 10.0.17134.706 (1803/April2018Update/Redstone4)
Intel Core i5-8250U CPU 1.60GHz (Kaby Lake R), 1 CPU, 8 logical and 4 physical cores
Frequency=1757813 Hz, Resolution=568.8887 ns, Timer=TSC
[Host] : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3394.0
DefaultJob : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3394.0
| Method | N | Mean | Error | StdDev |
|------------------------------- |------ |----------:|----------:|----------:|
| FindDadosEmpInCache | 30000 | 231.40 ns | 0.4435 ns | 0.3703 ns |
| FindDataAtTheEnd | 30000 | 429.90 ns | 1.1490 ns | 1.0186 ns |
| FindDataInDictionary | 30000 | 24.09 ns | 0.2244 ns | 0.2099 ns |
| FindDataInConcurrentDictionary | 30000 | 29.66 ns | 0.0990 ns | 0.0926 ns |
| FindDataInHashset | 30000 | 16.25 ns | 0.0077 ns | 0.0065 ns |
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
namespace TestListPerformance
{
class Program
{
static void Main(string[] args) {
var summary = BenchmarkRunner.Run<BenchmarkMemoryCache>();
}
}
public class BenchmarkMemoryCache
{
[Params(30000)]
public int N { get; set; }
public string FindStr;
private IList<DadosEmp> data;
private Dictionary<string, DadosEmp> dict;
private ConcurrentDictionary<string, DadosEmp> concurrentDict;
private HashSet<DadosEmp> hashset;
private DadosEmp last;
[GlobalSetup]
public void BuildData() {
FindStr = N.ToString();
data = new List<DadosEmp>(N);
dict = new Dictionary<string, DadosEmp>(N);
concurrentDict = new ConcurrentDictionary<string, DadosEmp>();
hashset = new HashSet<DadosEmp>();
for (int i = 0; i <= N; i++) {
DadosEmp d;
data.Add(d = new DadosEmp {
Identificacao = i,
Pis = i * 100,
NumCartao = i * 1000,
Nome = "Nome " + i.ToString(),
});
MemoryCache.Default.Add(i.ToString(), d,
new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(30) });
dict.Add(i.ToString(), d);
concurrentDict.TryAdd(i.ToString(), d);
hashset.Add(d);
last = d;
}
}
[Benchmark]
public DadosEmp FindDadosEmpInCache() {
var f = (DadosEmp)MemoryCache.Default.Get(FindStr);
return f;
}
[Benchmark]
public DadosEmp FindDataAtTheEnd() {
var f = data.FirstOrDefault(e => e.NumCartao == N || e.Pis == N || e.Identificacao == N);
return f;
}
[Benchmark]
public DadosEmp FindDataInDictionary() {
var f = dict[FindStr];
return f;
}
[Benchmark]
public DadosEmp FindDataInConcurrentDictionary() {
var f = concurrentDict[FindStr];
return f;
}
[Benchmark]
public bool FindDataInHashset() {
return hashset.Contains(last);
}
}
public class DadosEmp : IEquatable<DadosEmp>
{
public const string BIO_EXCLUSAO = "xbio";
public DadosEmp() {
Biometrias = new List<string>();
}
public long Identificacao { get; set; }
public long Pis { get; set; }
public long NumCartao { get; set; }
public string Nome { get; set; }
public int VersaoBio { get; set; }
public string Unidade { get; set; }
public IList<string> Biometrias { get; set; }
public string Biometria { get; set; }
public bool ExcluirBiometria { get { return Biometria == BIO_EXCLUSAO; } }
public DateTime DataEnvioRep { get; set; }
public string SenhaTeclado { get; set; }
public bool ExigeAutorizacaoSaida { get; set; }
public bool BioRepPendente { get; set; }
public override bool Equals(object obj) {
DadosEmp e = obj as DadosEmp;
if (ReferenceEquals(e, null))
return false;
return Equals(e);
}
public bool Equals(DadosEmp e) {
if (ReferenceEquals(e, null))
return false;
return e.Pis == this.Pis;
}
public override int GetHashCode() {
return Pis.GetHashCode();
}
public override string ToString() {
return string.Format("{0} ({1} - {2})", Nome, Pis, Identificacao);
}
}
}