Python代码比Java慢20倍。有没有办法加速Python?

时间:2016-09-12 21:56:06

标签: java python performance

我用Python和Java编写了一个程序来搜索等式的最小整数解:

a ^ 5 + b ^ 5 + c ^ 5 + d ^ 5 = e ^ 5(预期输出为133 ^ 5 + 110 ^ 5 + 84 ^ 5 + 27 ^ 5 = 144 ^ 5)

直接计算功率和根("直接计算"方法)或计算并存储在数组中("功率查找"方法)。查看第五个权力,如n5 = fifth_power [n]。使用数组' fifth_power`中的二进制搜索计算第五个幂根。

如果重要的话,我在NetBeans上运行它。需要:

Drupal\Core\Database\ConnectionNotDefinedException: The specified database connection is not defined: default in                                         [error]
/Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Core/Database/Database.php:361
Stack trace:
#0 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Core/Database/Database.php(166):
Drupal\Core\Database\Database::openConnection('default', 'default')
#1 [internal function]: Drupal\Core\Database\Database::getConnection('default')
#2 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(254): call_user_func_array(Array,
Array)
#3 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(177):
Drupal\Component\DependencyInjection\Container->createService(Array, 'database')
#4 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(494):
Drupal\Component\DependencyInjection\Container->get('database', 1)
#5 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(236):
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array)
#6 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(177):
Drupal\Component\DependencyInjection\Container->createService(Array, 'cache.backend.d...')
#7 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Core/Cache/ChainedFastBackendFactory.php(85):
Drupal\Component\DependencyInjection\Container->get('cache.backend.d...')
#8 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Core/Cache/CacheFactory.php(79):
Drupal\Core\Cache\ChainedFastBackendFactory->get('bootstrap')
#9 [internal function]: Drupal\Core\Cache\CacheFactory->get('bootstrap')
#10 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(254): call_user_func_array(Array,
Array)
#11 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(177):
Drupal\Component\DependencyInjection\Container->createService(Array, 'cache.bootstrap')
#12 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(494):
Drupal\Component\DependencyInjection\Container->get('cache.bootstrap', 1)
#13 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(236):
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array)
#14 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Component/DependencyInjection/Container.php(177):
Drupal\Component\DependencyInjection\Container->createService(Array, 'module_handler')
#15 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Core/DrupalKernel.php(520):
Drupal\Component\DependencyInjection\Container->get('module_handler')
#16 /Users/myusername/.kalabox/apps/canchascrd8/code/core/lib/Drupal/Core/DrupalKernel.php(678):
Drupal\Core\DrupalKernel->preHandle(Object(Symfony\Component\HttpFoundation\Request))
#17 /usr/local/Cellar/drush/8.1.3/libexec/lib/Drush/Boot/DrupalBoot8.php(150):
Drupal\Core\DrupalKernel->prepareLegacyRequest(Object(Symfony\Component\HttpFoundation\Request))
#18 /usr/local/Cellar/drush/8.1.3/libexec/includes/bootstrap.inc(354): Drush\Boot\DrupalBoot8->bootstrap_drupal_full()
#19 /usr/local/Cellar/drush/8.1.3/libexec/commands/user/user.drush.inc(389): drush_bootstrap(5)
#20 /usr/local/Cellar/drush/8.1.3/libexec/includes/command.inc(373): drush_user_login()
#21 /usr/local/Cellar/drush/8.1.3/libexec/includes/command.inc(224): _drush_invoke_hooks(Array, Array)
#22 /usr/local/Cellar/drush/8.1.3/libexec/includes/command.inc(192): drush_command()
#23 /usr/local/Cellar/drush/8.1.3/libexec/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#24 /usr/local/Cellar/drush/8.1.3/libexec/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#25 /usr/local/Cellar/drush/8.1.3/libexec/drush.php(12): drush_main()

有没有办法提升Python性能?我不是在寻找更好的数学(某种筛分)。我正在寻找更好的实现"对于a,b,c,d的每个组合计算它们的一些功率,检查总和是否是完美的功率。如果是 - 打印结果"。

预计Python运行速度比Java慢20倍吗?

Python 3.5

http://pastebin.com/qVthWGKm

30. s (Python, direct)
20. s (Python, lookup)
5.6 s (Java, direct)
0.8 s (Java, lookup)

Java 8:

http://pastebin.com/G4V3fHnD

from array import *
import math
import time

#PYTHON, BRUTEFORCE : ~30 s
millis1 = int(round(time.time() * 1000))
keep_searching = True
a=1
result=""
while(keep_searching):
    a+=1
    for b in range(1,a+1):
        for c in range(1,b+1):
            for d in range(1,c+1):
                sum=math.pow(a,5)+math.pow(b,5)+math.pow(c,5)+math.pow(d,5)
                root = math.pow(sum,0.2)
                e = round(root)


                e5 = math.pow(e,5)              

                if(e5==sum):
                    result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(int(a),int(b), int(c),int(d), int(e))
                    keep_searching = False
                    millis2 = int(round(time.time() * 1000))

print(result)
print("Found solution in {} ms".format(millis2-millis1))

#PYTHON, PRECOMPUTE POWERS: ~20 s
millis3 = int(round(time.time() * 1000))  
#fifth_power #175 is enough
size=176
fifth_power = [None] * size
for i in range(size):
    fifth_power[i]=long(math.pow(i,5))

millis4 = int(round(time.time() * 1000))  

#returns  value if it is a perfect power (32 returns 2)  
#returns -1 if between perfect powers, -2 if greater than max value in array, -3 if smaller than min value in array

def check_perfect_power(number, min, max, fifth_power):


    current=int((min+max)/2)
    while(max>=min):
        if(number==fifth_power[current]):
            return current
        elif(number>fifth_power[current]):
            min=current+1
            current=int((max+min)/2)
        else:
            max=current-1
            current=int((max+min)/2)

    if(min>=len(fifth_power)):        
        return -2
    if(max<0):
        return -3

    return -1  

keep_searching = True
a=0
result=""
while(keep_searching):
    a+=1
    for b in range(1,a+1):
        for c in range(1,b+1):
            for d in range(1,c+1):
                mymax=min(int(a*1.32)+1, size-1)
                e=check_perfect_power(fifth_power[a]+fifth_power[b]+fifth_power[c]+fifth_power[d], a, mymax, fifth_power)
                if(e>0):
                    result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(int(a),int(b), int(c),int(d), int(e))
                    keep_searching = False
                    millis5 = int(round(time.time() * 1000))

print(result)

    print("Populated in {} ms, find solution in {} ms".format(millis4-millis3,millis5-millis4))

2 个答案:

答案 0 :(得分:1)

from array import *
import time
import numpy as np

#PYTHON, BRUTEFORCE : ~30 s
millis1 = int(round(time.time() * 1000))
keep_searching = True
a = 1
result = ""
while(keep_searching):
    a += 1
    a_pow = a ** 5
    for b in xrange(1, a+1):
        b_pow = b ** 5
        for c in xrange(1, b+1):
            c_pow = c ** 5
            for d in xrange(1, c+1):
                d_pow = d ** 5
                sum_pow = a_pow + b_pow + c_pow + d_pow
                root = sum_pow ** 0.2
                e = round(root)


                e5 = e ** 5             

                if(e5 == sum_pow):
                    result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(a, b, c, d, e)
                    keep_searching = False
                    millis2 = int(round(time.time() * 1000))

print(result)
print("Found solution in {} ms".format(millis2-millis1))

Python 2.7,包含一些代码优化

133 ^ 5 + 110 ^ 5 + 84 ^ 5 + 27 ^ 5 = 144.0 ^ 5 在8333 ms找到解决方案

从CPU到CPU可能有点不同。

答案 1 :(得分:1)

如何改进java代码?

int size = 200;
long[] pow5 = new long[size];

for (int i = 1; i < size; ++i)
{
    long sqr = i * i;
    pow5[i] = sqr * sqr * i;
}

for (int a = 1; a < size; ++a)
{
    for (int b = 1; b <= a; ++b)
    {
        for (int c = 1; c <= b; ++c)
        {
            int e = a + 1;
            for (int d = 1; d <= c; ++d)
            {
                long sum = pow5[a] + pow5[b] + pow5[c] + pow5[d];
                while(pow5[e] < sum){ e++; }
                if (pow5[e] == sum)
                {
                    System.out.println(a + "^5 + " + b + "^5 + " + c + "^5 + " + d + "^5 = " + e + "^5");
                    return;
                }
            }
        }
    }
}