一个小优化记录

  用前面笔试题做机器学习时,由于需要数据集,所以要产生数据,但效率是个问题,于是用了C/C++来做,并且进行优化,这里有两种写法:

  1.if:

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

int64_t foo(int x)
{
	if (x <= 2)	return 1;
	else return foo(x - 2) + foo(x - 4) + 1;
}

int main()
{
	clock_t start, finish;
	
	int64_t y = 1;
	start = clock();
	for (int x = 81; x < 101; x++)
	{
		if ((x & 0x1) != 0) y = foo(x);
		printf("%d %lld\n", x, y);
	}
	finish = clock();
	printf("runtime finished:%lfs...\n", (double)((finish - start)/CLOCKS_PER_SEC));
	
	return 0;
}

  2.三目运算符:

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

int64_t foo(int x)
{
	if (x <= 2)	return 1;
	else return foo(x - 2) + foo(x - 4) + 1;
}

int main()
{
	clock_t start, finish;
	
	int64_t y = 1;
	start = clock();
	for (int x = 81; x < 101; x++)
	{
		(x & 0x1) != 0 ? y = foo(x) : y;
		printf("%d %lld\n", x, y);
	}
	finish = clock();
	printf("runtime finished:%lfs...\n", (double)((finish - start)/CLOCKS_PER_SEC));
	
	return 0;
}

  if(共运行7次,取其中3次结果):

[darkchii@localhost C++Projects]$ g++ -o test test.cpp
[darkchii@localhost C++Projects]$ ./test
81 535828591
...
100 40730022147
runtime finished:239.000000s...

[darkchii@localhost C++Projects]$ ./test
81 535828591
...
100 40730022147
runtime finished:225.000000s...

[darkchii@localhost C++Projects]$ ./test
81 535828591
...
100 40730022147
runtime finished:209.000000s...

  三目运算符(共运行7次,取其中3次结果):

[darkchii@localhost C++Projects]$ g++ -o test test.cpp
[darkchii@localhost C++Projects]$ ./test
81 535828591
...
100 40730022147
runtime finished:218.000000s...

[darkchii@localhost C++Projects]$ ./test
81 535828591
...
100 40730022147
runtime finished:217.000000s...

[darkchii@localhost C++Projects]$ ./test
81 535828591
...
100 40730022147
runtime finished:203.000000s...

  可以看到这里`?:`总是比`if-else`稍微快几s。。。

  当然实际上如果没有编译器的优化正常写法`?:`是要比`if-else`慢点的,比如:

x = (x > 0 ? x-- : x++);

  因为三目运算符是先运算后赋值。。。

 

  不过我不懂汇编,没有进行更严谨的分析,所以也不知道这里为什么使用三目效率更好一点...

  python就不说了,跑一晚上没跑出结果。。。

  一些参考:

    http://blog.sina.com.cn/s/blog_6cf502aa0101e7mx.html#post

    https://www.cnblogs.com/nietzsche-oier/p/6246440.html

转载于:https://www.cnblogs.com/darkchii/p/9154684.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值