C语言之测试程序运行时间

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int BitCount2(unsigned int n)  
{  
      
    unsigned int c =0 ;  
    while(n!=0)  
    {  
          
    n &= (n -1) ; // 清除最低位的1  
    c++;  
    }  
    return c ;  
}  
int BitCount4(unsigned int n)   
{   
    n = (n &0x55555555) + ((n >>1) &0x55555555) ;    //  n相邻位相加  
    n = (n &0x33333333) + ((n >>2) &0x33333333) ;    //  n(以2为单位)相邻位相加  
    n = (n &0x0f0f0f0f) + ((n >>4) &0x0f0f0f0f) ;    //  n(以4为单位)相邻位相加  
    n = (n &0x00ff00ff) + ((n >>8) &0x00ff00ff) ;    //  n(以8为单位)相邻位相加  
    n = (n &0x0000ffff) + ((n >>16) &0x0000ffff) ;   //  n(以16为单位)相邻位相加  
  
    return n ;   
}  
int  main( )
{
   long i=100000000;
   unsigned int n;
   clock_t start, finish; 
   double Total_time; 
   
    start = clock(); 
	while(--i)
	n=BitCount2(123456789);
	finish = clock(); 
	printf( "bit number::%d \n", n); 
    Total_time = (double)(finish-start) / CLOCKS_PER_SEC; 
    printf( "BitCount2::%f seconds\n", Total_time); 
	printf( "\n", n); 
	
	i=100000000;
	start = clock(); 
	while(--i)
	n=BitCount4(123456789);
	finish = clock(); 
    Total_time = (double)(finish-start) / CLOCKS_PER_SEC; 
	printf( "bit number::%d \n", n); 
    printf( "BitCount4::%f seconds\n", Total_time); 
	
	
  return 0;
}


运行结果:


如上所示:一个好的算法是多么重要。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值