极限速度对比测试:memcpy & =,long = (long*)int & long = (long*)long,15+15 & 123456789+123456789

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <string.h>
#include <sys/time.h>

#define TIME_DIFF(ts,te) ((te.tv_sec-ts.tv_sec)+(te.tv_usec-ts.tv_usec)*1.0/1000000)
int main(char** argv, int argc){
        long l,ll=12345656;
        int i,j=123456789, k=15;
        int *x = &j;
        void *z = (void*)&j;
        void *y = (void*)&y;

        struct timeval sts, ets;
        gettimeofday(&sts, NULL);
                                                           
        for(i=0;i<210000000;i++){
                memcpy(&l, &j, sizeof(int));
        }
        gettimeofday(&ets, NULL);
        double time_use = TIME_DIFF(sts, ets);
        printf("memcpy use time=%f\n", time_use);

        gettimeofday(&sts, NULL);
        for(i=0;i<210000000;i++){
                l = *x;
        }
        gettimeofday(&ets, NULL);
        time_use = TIME_DIFF(sts, ets);
        printf("=* use time=%f\n", time_use);

        gettimeofday(&sts, NULL);
        for(i=0;i<210000000;i++){
                l = *((int*)z);
        }
        gettimeofday(&ets, NULL);
        time_use = TIME_DIFF(sts, ets);
        printf("=void int int* use time=%f\n", time_use);

        gettimeofday(&sts, NULL);
        for(i=0;i<210000000;i++){
                l = *((long*)z);
        }
        gettimeofday(&ets, NULL);
        time_use = TIME_DIFF(sts, ets);
        printf("=void int void long* use time=%f\n", time_use);

        gettimeofday(&sts, NULL);
        for(i=0;i<210000000;i++){
                l = *((long*)y);
        }
        gettimeofday(&ets, NULL);
        time_use = TIME_DIFF(sts, ets);
        printf("=void long void long* use time=%f\n", time_use);


        gettimeofday(&sts, NULL);
        for(i=0;i<210000000;i++){
                l = j+j;
        }
        gettimeofday(&ets, NULL);
        time_use = TIME_DIFF(sts, ets);
        printf("123456789++ use time=%f\n", time_use);

        gettimeofday(&sts, NULL);
        for(i=0;i<210000000;i++){
                l = k+k;
        }
        gettimeofday(&ets, NULL);
        time_use = TIME_DIFF(sts, ets);
        printf("15++ use time=%f\n", time_use);

}

----------------------------------------------

memcpy use time=1.607823
=* use time=0.528125
=void int int* use time=0.483802
=void int void long* use time=1.104858
=void long void long* use time=0.471855
123456789++ use time=0.684760
15++ use time=0.562018

----------------------------------------------

memcpy use time=1.649806
=* use time=0.494963
=void int int* use time=0.562882
=void int void long* use time=1.303786
=void long void long* use time=0.469202
123456789++ use time=0.553262
15++ use time=0.572414
 

结论:

memcpy比=赋值慢!

int*强转long*需要额外耗时!

大数字相加和小数字相加速度相差无几。 

猜你喜欢

转载自blog.csdn.net/leinchu/article/details/86621464