switch与if 性能测试

测试结果:switch性能更高。

测试过程:新建一个Win32 Console Application, 在cpp文件中添加下面代码

#include "stdafx.h"
#include <Windows.h>


void SwitchTime(int a)
{     
  for (int i = 0; i < 1000000000; ++i)
  {    
    switch(a)
    {
    case 0:
      a = 0;
      break;

    case 1:
      a = 0;
      break;

    case 2:
      a = 0;
      break;

    case 3:
      a = 0;
      break;

    case 4:
      a = 0;
      break;

    case 5:
      a = 0;
      break;

    case 6:
      a = 0;
      break;

    case 7:
      a = 0;
      break;

    case 8:
      a = 0;
      break;

    case 9:
      a = 0;
      break;

    case 10:
      a = 0;
      break;

    case 11:
      a = 0;
      break;

    case 12:
      a = 0;
      break;

    case 13:
      a = 0;
      break;

    case 14:
      a = 0;
      break;

    case 15:
      a = 0;
      break;

    case 16:
      a = 0;
      break;

    case 17:
      a = 0;
      break;

    case 18:
      a = 0;
      break;

    case 19:
      a = 0;
      break;

    default:
      a = 0;
      break;
    }
  }   
}

void IfTime(int a)
{      
  for (int i = 0; i < 1000000000; ++i)
  {    
    if (0 == a)
    {
      a = 0;
    }
    else if (1 == a)
    {
      a = 0;
    }
    else if (2 == a)
    {
      a = 0;
    }
    else if (3 == a)
    {
      a = 0;
    }
    else if (4 == a)
    {
      a = 0;
    }
    else if (5 == a)
    {
      a = 0;
    }
    else if (6 == a)
    {
      a = 0;
    }
    else if (7 == a)
    {
      a = 0;
    }
    else if (8 == a)
    {
      a = 0;
    }
    else if (9 == a)
    {
      a = 0;
    }
    else if (10 == a)
    {
      a = 0;
    }
    else if (11 == a)
    {
      a = 0;
    }
    else if (12 == a)
    {
      a = 0;
    }
    else if (13 == a)
    {
      a = 0;
    }
    else if (14 == a)
    {
      a = 0;
    }
    else if (15 == a)
    {
      a = 0;
    }
    else if (16 == a)
    {
      a = 0;
    }
    else if (17 == a)
    {
      a = 0;
    }
    else if (18 == a)
    {
      a = 0;
    }
    else if (19 == a)
    {
      a = 0;
    }
    else
    {
      a = 0;
    }
  }   
}

int _tmain(int argc, _TCHAR* argv[])
{  
  unsigned long switchBegin= ::GetTickCount();
  SwitchTime(0);
  unsigned long switchEnd= ::GetTickCount();

  unsigned long ifBegin= ::GetTickCount();
  IfTime(0);
  unsigned long ifEnd= ::GetTickCount();

  char result[128];
  memset(result, 0, sizeof(result));
  sprintf(result, "SwitchTime: %d ms, IfTime: %d ms", switchEnd - switchBegin, ifEnd - ifBegin);
  MessageBoxA(NULL, result, "switch与if 性能测试", MB_OK);
  return 0;
}


分别测试输入值0、10、19、20、-1、200 

运行exe效果如下,

 

posted @ 2015-04-08 18:42  ~小小鸟~  阅读(518)  评论(0编辑  收藏  举报