随机数与取模结果对比

今日发现项目中在使用TBSchedule,对于生成的TaskItem数据,item是通过随机数生成的,如使用 new Random().nextInt(4)+1; 此运算会返回1~4的随机数字。其实这种做法是不均衡的,如果在少量数据时,对于数据的处理没有什么影响,但当有大数据量时,可能使个别服务器处理数据的压力加大, 因此我们最好通过取模方式来进行处理。比如对待处理的数据order_id取模。 order_id%+1,生成1~4的任务项。

针对上面提到不均衡的问题,进行简单测试统计如下:

复制代码
 1 public static void main(String[] args) {
 2         int size = 1000000;
 3         Map<Integer,Integer> map1 = new HashMap<Integer,Integer>();
 4         for(int i=1;i<size;i++) {
 5             int k = new Random().nextInt(4) + 1;
 6             if(map1.containsKey(k)){
 7                 map1.put(k, map1.get(k)+1);
 8             }else{
 9                 map1.put(k, 1);
10             }
11         }
12 
13         for(Map.Entry<Integer,Integer> entry:map1.entrySet()){
14             System.out.println(entry.getKey() + ":" + entry.getValue());
15         }
16 
17 
18         System.out.println("-----------------------------------");
19         Map<Integer,Integer> map2 = new HashMap<Integer,Integer>();
20         for(int i=1; i<size; i++){
21             int k = i%4+1;
22             if(map2.containsKey(k)){
23                 map2.put(k, map2.get(k)+1);
24             }else{
25                 map2.put(k, 1);
26             }
27         }
28 
29         for(Map.Entry<Integer,Integer> entry:map2.entrySet()){
30             System.out.println(entry.getKey() + ":" + entry.getValue());
31         }
32     }
复制代码

 测试结果:

1:250523
2:249897
3:249494
4:250085
-----------------------------------
1:249999
2:250000
3:250000
4:250000

由上面的结果可以看到,使用取模的方式,只差1; 而使用随机数就比较大了

posted @   blacksonny  阅读(1417)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示