翼度科技»论坛 编程开发 .net 查看内容

探索:优雅地实现异步方法的并行化

2

主题

2

帖子

6

积分

新手上路

Rank: 1

积分
6
接上篇 通过一个示例形象地理解C# async await 非并行异步、并行异步、并行异步的并发量控制
前些天写了两篇关于C# async await异步的博客,
第一篇博客看的人多,点赞评论也多,我想应该都看懂了,比较简单。
第二篇博客看的人少,点赞的也少,没有评论。
我很纳闷,第二篇博客才是重点,如此吊炸天的代码,居然没人评论。
博客中的代码,就是.NET圈的大佬也没有写过,为什么这么说?这就要说到C# async await的语法糖了:
没有语法糖,代码一样写,java8没有语法糖,一样能写出高性能代码。但有了C# async await语法糖,水平一般的普通的业务程序员,哪怕很菜,也能写出高性能高吞吐量的代码,这就是意义!
所以我说顶级大佬没写过,因为他们水平高,脑力好,手段多,自然不需要这么写。但对于普通程序来说,代码写的复杂了,麻烦不说,BUG频出。
标题我用了"探索"这个词,有没有更好的实践,让小白们都容易写的并行异步的实践?
ElasticSearch的性能

下面通过一个es的查询,来展示并行异步代码的实用价值。
下面是真实环境中部署的服务的测试截图:

379次es查询,仅需0.185秒(当然耗时会有波动,零点几秒都是正常的)。
es最怕的是什么?是慢查询,是条件复杂的大范围模糊查询。
我的策略是多次精确查询,这样可以利用es极高的吞吐能力。
有多快?


  • 上述截图只是其中一个测试,查询分析的时间范围较小(一个多月的数据量)
  • 另一个服务接口,分析半年的数据量,大约72亿+18亿=90亿,从这些数据中分析出结果,仅需大约3-6秒。
为什么这么快?


  • es集群的服务器较多,内存很大(300G,当然服务器上不只有es),集群本身的吞吐量很高。
  • 并行异步性能高且吞吐量大!而C#语法糖使得并行异步容易编写。
为什么要使用并行异步?

既然查询次数多,单线程或同步方式肯定是不行的,必须并行查询。
并行代码,python、java也能写。
但前同事写的在双层循环体中多次查询es的python代码,就是同步方式。为什么不并行查询呢?并行肯定可以写,但是能不写就不写,为什么?因为写起来复杂,不好写,不好调试,还容易写出BUG。
重点是什么?不仅要写并行代码,还要写的简单,不破坏代码原有逻辑结构。
普通的异步方法

普通的异步方法大家都会写,用async await就行了,很简单。下面是我自己写的,主要是在双循环中多次异步请求(由于是实际代码,不是Demo,所以代码有点长,可以大致看一下,主要看await xxx是怎样写的):
  1. /// <summary>
  2. /// xxx查询
  3. /// </summary>
  4. public async Task<List<AccompanyInfo>> Query2(string strStartTime, string strEndTime, int kpCountThreshold, int countThreshold, int distanceThreshold, int timeThreshold, List<PeopleCluster> peopleClusterList)
  5. {
  6.     List<AccompanyInfo> resultList = new List<AccompanyInfo>();
  7.     Stopwatch sw = Stopwatch.StartNew();
  8.     //创建字典
  9.     Dictionary<string, PeopleCluster> clusterIdPeopleDict = new Dictionary<string, PeopleCluster>();
  10.     foreach (PeopleCluster peopleCluster in peopleClusterList)
  11.     {
  12.         foreach (string clusterId in peopleCluster.ClusterIds)
  13.         {
  14.             if (!clusterIdPeopleDict.ContainsKey(clusterId))
  15.             {
  16.                 clusterIdPeopleDict.Add(clusterId, peopleCluster);
  17.             }
  18.         }
  19.     }
  20.     int queryCount = 0;
  21.     Dictionary<string, AccompanyInfo> dict = new Dictionary<string, AccompanyInfo>();
  22.     foreach (PeopleCluster people1 in peopleClusterList)
  23.     {
  24.         List<PeopleFeatureInfo> peopleFeatureList = await ServiceFactory.Get<PeopleFeatureQueryService>().Query(strStartTime, strEndTime, people1);
  25.         queryCount++;
  26.         foreach (PeopleFeatureInfo peopleFeatureInfo1 in peopleFeatureList)
  27.         {
  28.             DateTime capturedTime = DateTime.ParseExact(peopleFeatureInfo1.captured_time, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
  29.             string strStartTime2 = capturedTime.AddSeconds(-timeThreshold).ToString("yyyyMMddHHmmss");
  30.             string strEndTime2 = capturedTime.AddSeconds(timeThreshold).ToString("yyyyMMddHHmmss");
  31.             List<PeopleFeatureInfo> peopleFeatureList2 = await ServiceFactory.Get<PeopleFeatureQueryService>().QueryExcludeSelf(strStartTime2, strEndTime2, people1);
  32.             queryCount++;
  33.             if (peopleFeatureList2.Count > 0)
  34.             {
  35.                 foreach (PeopleFeatureInfo peopleFeatureInfo2 in peopleFeatureList2)
  36.                 {
  37.                     string key = null;
  38.                     PeopleCluster people2 = null;
  39.                     string people2ClusterId = null;
  40.                     if (clusterIdPeopleDict.ContainsKey(peopleFeatureInfo2.cluster_id.ToString()))
  41.                     {
  42.                         people2 = clusterIdPeopleDict[peopleFeatureInfo2.cluster_id.ToString()];
  43.                         key = $"{string.Join(",", people1.ClusterIds)}_{string.Join(",", people2.ClusterIds)}";
  44.                     }
  45.                     else
  46.                     {
  47.                         people2ClusterId = peopleFeatureInfo2.cluster_id.ToString();
  48.                         key = $"{string.Join(",", people1.ClusterIds)}_{string.Join(",", people2ClusterId)}";
  49.                     }
  50.                     double distance = LngLatUtil.CalcDistance(peopleFeatureInfo1.Longitude, peopleFeatureInfo1.Latitude, peopleFeatureInfo2.Longitude, peopleFeatureInfo2.Latitude);
  51.                     if (distance > distanceThreshold) continue;
  52.                     AccompanyInfo accompanyInfo;
  53.                     if (dict.ContainsKey(key))
  54.                     {
  55.                         accompanyInfo = dict[key];
  56.                     }
  57.                     else
  58.                     {
  59.                         accompanyInfo = new AccompanyInfo();
  60.                         dict.Add(key, accompanyInfo);
  61.                     }
  62.                     accompanyInfo.People1 = people1;
  63.                     if (people2 != null)
  64.                     {
  65.                         accompanyInfo.People2 = people2;
  66.                     }
  67.                     else
  68.                     {
  69.                         accompanyInfo.ClusterId2 = people2ClusterId;
  70.                     }
  71.                     AccompanyItem accompanyItem = new AccompanyItem();
  72.                     accompanyItem.Info1 = peopleFeatureInfo1;
  73.                     accompanyItem.Info2 = peopleFeatureInfo2;
  74.                     accompanyInfo.List.Add(accompanyItem);
  75.                     accompanyInfo.Count++;
  76.                     resultList.Add(accompanyInfo);
  77.                 }
  78.             }
  79.         }
  80.     }
  81.     resultList = resultList.FindAll(a => (a.People2 != null && a.Count >= kpCountThreshold) || a.Count >= countThreshold);
  82.     //去重
  83.     int beforeDistinctCount = resultList.Count;
  84.     resultList = resultList.DistinctBy(a =>
  85.     {
  86.         string str1 = string.Join(",", a.People1.ClusterIds);
  87.         string str2 = a.People2 != null ? string.Join(",", a.People2.ClusterIds) : string.Empty;
  88.         string str3 = a.ClusterId2 ?? string.Empty;
  89.         StringBuilder sb = new StringBuilder();
  90.         foreach (AccompanyItem item in a.List)
  91.         {
  92.             var info2 = item.Info2;
  93.             sb.Append($"{info2.camera_id},{info2.captured_time},{info2.cluster_id}");
  94.         }
  95.         return $"{str1}_{str2}_{str3}_{sb}";
  96.     }).ToList();
  97.     sw.Stop();
  98.     string msg = $"xxx查询,耗时:{sw.Elapsed.TotalSeconds:0.000} 秒,查询次数:{queryCount},去重:{beforeDistinctCount}-->{resultList.Count}";
  99.     Console.WriteLine(msg);
  100.     LogUtil.Info(msg);
  101.     return resultList;
  102. }
复制代码
异步方法的并行化

上述代码逻辑上是没有问题的,但性能上有问题。在双循环中多次请求,虽然用了async await异步,但不是并行,耗时会很长,如何优化?下面是并行异步的写法(由于是实际代码,不是Demo,所以代码有点长,可以大致看一下,主要看tasks1和tasks2怎样组织,怎样await,以及返回值怎么获取):
  1. /// <summary>
  2. /// xxx查询
  3. /// </summary>
  4. public async Task<List<AccompanyInfo>> Query(string strStartTime, string strEndTime, int kpCountThreshold, int countThreshold, int distanceThreshold, int timeThreshold, List<PeopleCluster> peopleClusterList)
  5. {
  6.     List<AccompanyInfo> resultList = new List<AccompanyInfo>();
  7.     Stopwatch sw = Stopwatch.StartNew();
  8.     //创建字典
  9.     Dictionary<string, PeopleCluster> clusterIdPeopleDict = new Dictionary<string, PeopleCluster>();
  10.     foreach (PeopleCluster peopleCluster in peopleClusterList)
  11.     {
  12.         foreach (string clusterId in peopleCluster.ClusterIds)
  13.         {
  14.             if (!clusterIdPeopleDict.ContainsKey(clusterId))
  15.             {
  16.                 clusterIdPeopleDict.Add(clusterId, peopleCluster);
  17.             }
  18.         }
  19.     }
  20.     //组织第一层循环task
  21.     Dictionary<PeopleCluster, Task<List<PeopleFeatureInfo>>> tasks1 = new Dictionary<PeopleCluster, Task<List<PeopleFeatureInfo>>>();
  22.     foreach (PeopleCluster people1 in peopleClusterList)
  23.     {
  24.         var task1 = ServiceFactory.Get<PeopleFeatureQueryService>().Query(strStartTime, strEndTime, people1);
  25.         tasks1.Add(people1, task1);
  26.     }
  27.     //计算第一层循环task并缓存结果,组织第二层循环task
  28.     Dictionary<string, Task<List<PeopleFeatureInfo>>> tasks2 = new Dictionary<string, Task<List<PeopleFeatureInfo>>>();
  29.     Dictionary<PeopleCluster, List<PeopleFeatureInfo>> cache1 = new Dictionary<PeopleCluster, List<PeopleFeatureInfo>>();
  30.     foreach (PeopleCluster people1 in peopleClusterList)
  31.     {
  32.         List<PeopleFeatureInfo> peopleFeatureList = await tasks1[people1];
  33.         cache1.Add(people1, peopleFeatureList);
  34.         foreach (PeopleFeatureInfo peopleFeatureInfo1 in peopleFeatureList)
  35.         {
  36.             DateTime capturedTime = DateTime.ParseExact(peopleFeatureInfo1.captured_time, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
  37.             string strStartTime2 = capturedTime.AddSeconds(-timeThreshold).ToString("yyyyMMddHHmmss");
  38.             string strEndTime2 = capturedTime.AddSeconds(timeThreshold).ToString("yyyyMMddHHmmss");
  39.             var task2 = ServiceFactory.Get<PeopleFeatureQueryService>().QueryExcludeSelf(strStartTime2, strEndTime2, people1);
  40.             string task2Key = $"{strStartTime2}_{strEndTime2}_{string.Join(",", people1.ClusterIds)}";
  41.             tasks2.TryAdd(task2Key, task2);
  42.         }
  43.     }
  44.     //读取第一层循环task缓存结果,计算第二层循环task
  45.     Dictionary<string, AccompanyInfo> dict = new Dictionary<string, AccompanyInfo>();
  46.     foreach (PeopleCluster people1 in peopleClusterList)
  47.     {
  48.         List<PeopleFeatureInfo> peopleFeatureList = cache1[people1];
  49.         foreach (PeopleFeatureInfo peopleFeatureInfo1 in peopleFeatureList)
  50.         {
  51.             DateTime capturedTime = DateTime.ParseExact(peopleFeatureInfo1.captured_time, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
  52.             string strStartTime2 = capturedTime.AddSeconds(-timeThreshold).ToString("yyyyMMddHHmmss");
  53.             string strEndTime2 = capturedTime.AddSeconds(timeThreshold).ToString("yyyyMMddHHmmss");
  54.             string task2Key = $"{strStartTime2}_{strEndTime2}_{string.Join(",", people1.ClusterIds)}";
  55.             List<PeopleFeatureInfo> peopleFeatureList2 = await tasks2[task2Key];
  56.             if (peopleFeatureList2.Count > 0)
  57.             {
  58.                 foreach (PeopleFeatureInfo peopleFeatureInfo2 in peopleFeatureList2)
  59.                 {
  60.                     string key = null;
  61.                     PeopleCluster people2 = null;
  62.                     string people2ClusterId = null;
  63.                     if (clusterIdPeopleDict.ContainsKey(peopleFeatureInfo2.cluster_id.ToString()))
  64.                     {
  65.                         people2 = clusterIdPeopleDict[peopleFeatureInfo2.cluster_id.ToString()];
  66.                         key = $"{string.Join(",", people1.ClusterIds)}_{string.Join(",", people2.ClusterIds)}";
  67.                     }
  68.                     else
  69.                     {
  70.                         people2ClusterId = peopleFeatureInfo2.cluster_id.ToString();
  71.                         key = $"{string.Join(",", people1.ClusterIds)}_{string.Join(",", people2ClusterId)}";
  72.                     }
  73.                     double distance = LngLatUtil.CalcDistance(peopleFeatureInfo1.Longitude, peopleFeatureInfo1.Latitude, peopleFeatureInfo2.Longitude, peopleFeatureInfo2.Latitude);
  74.                     if (distance > distanceThreshold) continue;
  75.                     AccompanyInfo accompanyInfo;
  76.                     if (dict.ContainsKey(key))
  77.                     {
  78.                         accompanyInfo = dict[key];
  79.                     }
  80.                     else
  81.                     {
  82.                         accompanyInfo = new AccompanyInfo();
  83.                         dict.Add(key, accompanyInfo);
  84.                     }
  85.                     accompanyInfo.People1 = people1;
  86.                     if (people2 != null)
  87.                     {
  88.                         accompanyInfo.People2 = people2;
  89.                     }
  90.                     else
  91.                     {
  92.                         accompanyInfo.ClusterId2 = people2ClusterId;
  93.                     }
  94.                     AccompanyItem accompanyItem = new AccompanyItem();
  95.                     accompanyItem.Info1 = peopleFeatureInfo1;
  96.                     accompanyItem.Info2 = peopleFeatureInfo2;
  97.                     accompanyInfo.List.Add(accompanyItem);
  98.                     accompanyInfo.Count++;
  99.                     resultList.Add(accompanyInfo);
  100.                 }
  101.             }
  102.         }
  103.     }
  104.     resultList = resultList.FindAll(a => (a.People2 != null && a.Count >= kpCountThreshold) || a.Count >= countThreshold);
  105.     //去重
  106.     int beforeDistinctCount = resultList.Count;
  107.     resultList = resultList.DistinctBy(a =>
  108.     {
  109.         string str1 = string.Join(",", a.People1.ClusterIds);
  110.         string str2 = a.People2 != null ? string.Join(",", a.People2.ClusterIds) : string.Empty;
  111.         string str3 = a.ClusterId2 ?? string.Empty;
  112.         StringBuilder sb = new StringBuilder();
  113.         foreach (AccompanyItem item in a.List)
  114.         {
  115.             var info2 = item.Info2;
  116.             sb.Append($"{info2.camera_id},{info2.captured_time},{info2.cluster_id}");
  117.         }
  118.         return $"{str1}_{str2}_{str3}_{sb}";
  119.     }).ToList();
  120.     //排序
  121.     foreach (AccompanyInfo item in resultList)
  122.     {
  123.         item.List.Sort((a, b) => -string.Compare(a.Info1.captured_time, b.Info1.captured_time));
  124.     }
  125.     sw.Stop();
  126.     string msg = $"xxx查询,耗时:{sw.Elapsed.TotalSeconds:0.000} 秒,查询次数:{tasks1.Count + tasks2.Count},去重:{beforeDistinctCount}-->{resultList.Count}";
  127.     Console.WriteLine(msg);
  128.     LogUtil.Info(msg);
  129.     return resultList;
  130. }
复制代码
上述代码说明


  • 为了使异步并行化,业务逻辑的双层循环要写三遍。第三遍双层循环代码结构和前面所述普通的异步方法中的双层循环代码结构是一样的。
  • 第一、二遍双层循环代码是多出来的。第一遍只有一层循环。第二遍有两层循环(第三层循环是处理数据和请求无关,这里不讨论)。
  • 写的时候,可以先写好普通的异步方法,然后再通过复粘贴修改成并行化的异步方法。当然,脑力好的可以直接写。
为什么说.NET圈的大佬没有写过?


  • 我觉得还真没有人这样写过!
  • 不吹个牛,博客没人看,没人点赞啊?!
  • 厉害的是C#,由于C#语法糖,把优秀的代码写简单了,才是真的优秀。
  • 我倒是希望有大佬写个更好的实践,把我这种写法淘汰掉,因为这是我能想到的最容易控制的写法了。
  • 并行代码,很多人都会写,java、python也能写,但问题是,水平一般的普通的业务程序员,如何无脑地写这种并行代码?
  • 最差的写法,例如java的CompletableFuture,和复杂的业务逻辑结合起来,写法就很复杂了。
  • 其次的写法,也是官方文档上有的,大家都能想到的写法,例如:
  1. List<PeopleFeatureInfo>[] listArray = await Task.WhenAll(tasks2.Values);
复制代码
在双循环体中,怎么拿结果?肯定能拿,但又要思考怎么写了不是?
而我的写法,在双循环体中是可以直接拿结果的:
  1. List<PeopleFeatureInfo> list = await tasks2[task2Key];
复制代码
并行代码用Python怎么写?

只放C#代码没有说服力,python代码我不太会写,不过,一个同事python写的很6,他写的数据挖掘代码很多都是并行,例如:
  1. def get_es_multiprocess(index_list, people_list, core_percent, rev_clusterid_idcard_dict):
  2.     '''
  3.     多进程读取es数据,转为整个数据帧,按时间排序
  4.     :return: 规模较大的数据帧
  5.     '''
  6.     col_list = ["cluster_id", "camera_id", "captured_time"]
  7.     pool = Pool(processes=int(mp.cpu_count() * core_percent))
  8.     input_list = [(i, people_list, col_list) for i in index_list]
  9.     res = pool.map(get_es, input_list)
  10.     if not res:
  11.         return None
  12.     pool.close()
  13.     pool.join()
  14.     df_all = pd.DataFrame(columns=col_list+['longitude', 'latitude'])
  15.     for df in res:
  16.         df_all = pd.concat([df_all, df])
  17.     # 这里强制转换为字符串!
  18.     df_all['cluster_id_'] = df_all['cluster_id'].apply(lambda x: rev_clusterid_idcard_dict[str(x)])
  19.     del df_all['cluster_id']
  20.     df_all.rename(columns={'cluster_id_': 'cluster_id'}, inplace=True)
  21.     df_all.sort_values(by='captured_time', inplace=True)
  22.     print('=' * 100)
  23.     print('整个数据(聚类前):')
  24.     print(df_all.info())
  25.     cluster_id_list = [(i, df) for i, df in df_all.groupby(['cluster_id'])]
  26.     cluster_id_list_split = [j for j in func(cluster_id_list, 1000000)]
  27.     # todo 缩小数据集,用于调试!
  28.     data_all = df_all.iloc[:, :]
  29.     return data_all, cluster_id_list_split
复制代码
上述python代码解析


  • 核心代码:
  1. res = pool.map(get_es, input_list)
  2. ...省略
  3. pool.join()
  4. ...省略
复制代码
核心代码说明:其中get_es是查询es的方法,应该不是异步方法,不过这不是重点
2. res是查询结果,通过并行的方式一次性查出来,放到res中,然后把结果再解出来
3. 注意,这只是单层循环,想想双层循环怎么写
4. pool.join()会阻塞当前线程,失去异步的好处,这个不好
5. 同事注释中写的是"多进程",是写错了吗?实际是多线程?还是多进程?
6. 当然,python是有async await异步写法的,应该不比C#差,只是同事没有使用
7. python代码,字符串太多,字符串是最不好维护的。我写的C#代码中的字符串里面都是强类型变量。
把脑力活变成体力活

照葫芦画瓢,把脑力活变成体力活,我又写了一个并行异步方法(业务逻辑依然有点复杂,主要看tasks1和tasks2怎样组织,怎样await,以及返回值怎么获取,注释"比对xxx"下面的代码和并行异步无关,可以略过):
  1. /// <summary>
  2. /// xxx查询
  3. /// </summary>
  4. public async Task<List<SameVehicleInfo>> Query(string strStartTime, string strEndTime, int kpCountThreshold, int timeThreshold, List<PeopleCluster> peopleClusterList)
  5. {
  6.     List<SameVehicleInfo> resultList = new List<SameVehicleInfo>();
  7.     Stopwatch sw = Stopwatch.StartNew();
  8.     //组织第一层循环task,查xxx
  9.     Dictionary<PeopleCluster, Task<List<PeopleFeatureInfo>>> tasks1 = new Dictionary<PeopleCluster, Task<List<PeopleFeatureInfo>>>();
  10.     foreach (PeopleCluster people1 in peopleClusterList)
  11.     {
  12.         var task1 = ServiceFactory.Get<PeopleFeatureQueryService>().Query(strStartTime, strEndTime, people1);
  13.         tasks1.Add(people1, task1);
  14.     }
  15.     //计算第一层循环task并缓存结果,组织第二层循环task,精确搜xxx
  16.     Dictionary<string, Task<List<MotorVehicleInfo>>> tasks2 = new Dictionary<string, Task<List<MotorVehicleInfo>>>();
  17.     Dictionary<PeopleCluster, List<PeopleFeatureInfo>> cache1 = new Dictionary<PeopleCluster, List<PeopleFeatureInfo>>();
  18.     foreach (PeopleCluster people1 in peopleClusterList)
  19.     {
  20.         List<PeopleFeatureInfo> peopleFeatureList = await tasks1[people1];
  21.         cache1.Add(people1, peopleFeatureList);
  22.         foreach (PeopleFeatureInfo peopleFeatureInfo1 in peopleFeatureList)
  23.         {
  24.             string task2Key = $"{peopleFeatureInfo1.camera_id}_{peopleFeatureInfo1.captured_time}";
  25.             var task2 = ServiceFactory.Get<MotorVehicleQueryService>().QueryExact(peopleFeatureInfo1.camera_id, peopleFeatureInfo1.captured_time);
  26.             tasks2.TryAdd(task2Key, task2);
  27.         }
  28.     }
  29.     //读取第一层循环task缓存结果,计算第二层循环task
  30.     Dictionary<PersonVehicleKey, PersonVehicleInfo> dictPersonVehicle = new Dictionary<PersonVehicleKey, PersonVehicleInfo>();
  31.     foreach (PeopleCluster people1 in peopleClusterList)
  32.     {
  33.         List<PeopleFeatureInfo> peopleFeatureList = cache1[people1];
  34.         foreach (PeopleFeatureInfo peopleFeatureInfo1 in peopleFeatureList)
  35.         {
  36.             string task2Key = $"{peopleFeatureInfo1.camera_id}_{peopleFeatureInfo1.captured_time}";
  37.             List<MotorVehicleInfo> motorVehicleList = await tasks2[task2Key];
  38.             motorVehicleList = motorVehicleList.DistinctBy(a => a.plate_no).ToList();
  39.             foreach (MotorVehicleInfo motorVehicleInfo in motorVehicleList)
  40.             {
  41.                 PersonVehicleKey key = new PersonVehicleKey(people1, motorVehicleInfo.plate_no);
  42.                 PersonVehicleInfo personVehicleInfo;
  43.                 if (dictPersonVehicle.ContainsKey(key))
  44.                 {
  45.                     personVehicleInfo = dictPersonVehicle[key];
  46.                 }
  47.                 else
  48.                 {
  49.                     personVehicleInfo = new PersonVehicleInfo()
  50.                     {
  51.                         People = people1,
  52.                         PlateNo = motorVehicleInfo.plate_no,
  53.                         List = new List<PeopleFeatureInfo>()
  54.                     };
  55.                     dictPersonVehicle.Add(key, personVehicleInfo);
  56.                 }
  57.                 personVehicleInfo.List.Add(peopleFeatureInfo1);
  58.             }
  59.         }
  60.     }
  61.     //比对xxx
  62.     List<PersonVehicleKey> keys = dictPersonVehicle.Keys.ToList();
  63.     Dictionary<string, SameVehicleInfo> dict = new Dictionary<string, SameVehicleInfo>();
  64.     for (int i = 0; i < keys.Count - 1; i++)
  65.     {
  66.         for (int j = i + 1; j < keys.Count; j++)
  67.         {
  68.             var key1 = keys[i];
  69.             var key2 = keys[j];
  70.             var personVehicle1 = dictPersonVehicle[key1];
  71.             var personVehicle2 = dictPersonVehicle[key2];
  72.             if (key1.PlateNo == key2.PlateNo)
  73.             {
  74.                 foreach (PeopleFeatureInfo peopleFeature1 in personVehicle1.List)
  75.                 {
  76.                     double minTimeDiff = double.MaxValue;
  77.                     int minIndex = -1;
  78.                     for (int k = 0; k < personVehicle2.List.Count; k++)
  79.                     {
  80.                         PeopleFeatureInfo peopleFeature2 = personVehicle2.List[k];
  81.                         DateTime capturedTime1 = DateTime.ParseExact(peopleFeature1.captured_time, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
  82.                         DateTime capturedTime2 = DateTime.ParseExact(peopleFeature2.captured_time, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
  83.                         var timeDiff = Math.Abs(capturedTime2.Subtract(capturedTime1).TotalSeconds);
  84.                         if (timeDiff < minTimeDiff)
  85.                         {
  86.                             minTimeDiff = timeDiff;
  87.                             minIndex = k;
  88.                         }
  89.                     }
  90.                     if (minIndex >= 0 && minTimeDiff <= timeThreshold * 60)
  91.                     {
  92.                         PeopleCluster people1 = key1.People;
  93.                         PeopleCluster people2 = key2.People;
  94.                         PeopleFeatureInfo peopleFeatureInfo2 = personVehicle2.List[minIndex];
  95.                         string key = $"{string.Join(",", people1.ClusterIds)}_{string.Join(",", people2.ClusterIds)}"; ;
  96.                         SameVehicleInfo accompanyInfo;
  97.                         if (dict.ContainsKey(key))
  98.                         {
  99.                             accompanyInfo = dict[key];
  100.                         }
  101.                         else
  102.                         {
  103.                             accompanyInfo = new SameVehicleInfo();
  104.                             dict.Add(key, accompanyInfo);
  105.                         }
  106.                         accompanyInfo.People1 = people1;
  107.                         accompanyInfo.People2 = people2;
  108.                         SameVehicleItem accompanyItem = new SameVehicleItem();
  109.                         accompanyItem.Info1 = peopleFeature1;
  110.                         accompanyItem.Info2 = peopleFeatureInfo2;
  111.                         accompanyInfo.List.Add(accompanyItem);
  112.                         accompanyInfo.Count++;
  113.                         resultList.Add(accompanyInfo);
  114.                     }
  115.                 }
  116.             }
  117.         }
  118.     }
  119.     resultList = resultList.FindAll(a => a.Count >= kpCountThreshold);
  120.     //筛选,排除xxx
  121.     resultList = resultList.FindAll(a =>
  122.     {
  123.         if (string.Join(",", a.People1.ClusterIds) == string.Join(",", a.People2.ClusterIds))
  124.         {
  125.             return false;
  126.         }
  127.         return true;
  128.     });
  129.     //去重
  130.     int beforeDistinctCount = resultList.Count;
  131.     resultList = resultList.DistinctBy(a =>
  132.     {
  133.         string str1 = string.Join(",", a.People1.ClusterIds);
  134.         string str2 = string.Join(",", a.People2.ClusterIds);
  135.         StringBuilder sb = new StringBuilder();
  136.         foreach (SameVehicleItem item in a.List)
  137.         {
  138.             var info2 = item.Info2;
  139.             sb.Append($"{info2.camera_id},{info2.captured_time},{info2.cluster_id}");
  140.         }
  141.         return $"{str1}_{str2}_{sb}";
  142.     }).ToList();
  143.     //排序
  144.     foreach (SameVehicleInfo item in resultList)
  145.     {
  146.         item.List.Sort((a, b) => -string.Compare(a.Info1.captured_time, b.Info1.captured_time));
  147.     }
  148.     sw.Stop();
  149.     string msg = $"xxx查询,耗时:{sw.Elapsed.TotalSeconds:0.000} 秒,查询次数:{tasks1.Count + tasks2.Count},去重:{beforeDistinctCount}-->{resultList.Count}";
  150.     Console.WriteLine(msg);
  151.     LogUtil.Info(msg);
  152.     return resultList;
  153. }
复制代码
C#的优点


  • 有人说:我们开发的低代码平台很优秀。C#:我就是低代码!
  • 有人说:我们开发的平台功能很强大,支持写SQL、支持写脚本。C#:我就是脚本语言!
  • 有人说:我们用spark、flink分布式。C#:并行异步高性能高吞吐,单机就可以,只要kafka和es是集群就行。

来源:https://www.cnblogs.com/s0611163/archive/2023/02/09/17098841.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具