用前面笔试题做机器学习时,由于需要数据集,所以要产生数据,但效率是个问题,于是用了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