Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1759432
  • 博文数量: 198
  • 博客积分: 4088
  • 博客等级: 上校
  • 技术积分: 2391
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-15 16:29
个人简介

游戏开发,系统架构; 博客迁移到:http://www.jianshu.com/u/3ac0504b3b8c

文章分类

全部博文(198)

文章存档

2017年(1)

2016年(12)

2015年(1)

2014年(3)

2013年(13)

2012年(18)

2011年(150)

分类: C/C++

2011-11-08 09:19:06

   以前编程的时候,对于索引的计算时间基本忽略,但是当数据量很大的时候,这些索引计算的时间累加起来也是很大的时间开销,下面用实例分析
  1. #include <iostream>
  2. #include <time.h>
  3. #include <map>

  4. using namespace std;

  5. struct KillEvent
  6. {
  7.     KillEvent()
  8.         :killerId(0)
  9.         ,bekillerId(0)
  10.     {
  11.     }
  12.     KillEvent(int killerid, int bekillerid)
  13.         :killerId(killerid)
  14.         ,bekillerId(bekillerid)
  15.     {
  16.     }

  17.     int killerId;
  18.     int bekillerId;
  19. };

  20. struct PlayerScore
  21. {
  22.     PlayerScore()
  23.         :userId(0)
  24.         ,score1(0)
  25.         ,score2(0)
  26.         ,score3(0)
  27.     {
  28.     }

  29.     PlayerScore(int userid)
  30.         :userId(userid)
  31.         ,score1(0)
  32.         ,score2(0)
  33.         ,score3(0)
  34.     {
  35.     }

  36.     int userId;
  37.     int score1;
  38.     int score2;
  39.     int score3;
  40. };

  41. map<int, KillEvent>        g_killEvent;
  42. map<int, PlayerScore>    g_playerScoreList;

  43. int main()
  44. {
  45.     clock_t start, end;

  46.     for(int i = 0; i < 10000; ++i)
  47.     {
  48.         g_playerScoreList[i] = PlayerScore(i);
  49.     }

  50.     for(int i = 0; i < 1000000; ++i)
  51.     {
  52.         g_killEvent[i] = KillEvent(i,(i + 100) %1000000);
  53.     }

  54.     start = clock();

  55.     for(int i = 0; i < g_killEvent.size(); ++i)
  56.     {
  57.         g_playerScoreList[g_killEvent[i].killerId].score1 += 10;
  58.         g_playerScoreList[g_killEvent[i].killerId].score2 += 5;
  59.         g_playerScoreList[g_killEvent[i].killerId].score3 += 3;

  60.         /*int index = g_killEvent[i].killerId;

  61.         g_playerScoreList[index].score1 += 10;
  62.         g_playerScoreList[index].score2 += 5;
  63.         g_playerScoreList[index].score3 += 3;*/
  64.     }

  65.     end = clock();

  66.     cout << "total use " << (end - start) /CLOCKS_PER_SEC << " s" << endl;

  67.     system("pause");

  68.     return 0;
  69. }

直接使用索引的结果是

:total use 45 s

将索引计算的结果保存下来的计算结果是

:total use 34 s

所以在一些大数据量处理的时候,我们千万不要忽略索引本身的计算开销

阅读(1161) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~