4

我惊讶地发现 Python 在获取索引位置方面比 PHP 慢。有没有办法提高 Python 的性能?

例如:

在 PHP 中花费:18.169965982437

<?php
$time_start = microtime(true);
$needle = file_get_contents("needle.wav", false, null, 46);

foreach(range(0, 10000) as $num) {
   $haystack = file_get_contents("haystack.wav");
   $match = strpos($haystack,$needle);
}

$time_end = microtime(true);

$finishTime = $time_end - $time_start;
echo $finishTime;
?>

在 Python 中需要:23.6319999695

import time
import math
def microtime(get_as_float = False) :
    if get_as_float:
        return time.time()
    else:
        return '%f %d' % math.modf(time.time())

time_start = microtime(True)
needle = open("needle.wav","rb").read()

for x in range(0, 10000):
    haystack = open("haystack.wav","rb").read()
    match = haystack.index(needle[46:])

time_end = microtime(True)
finishTime = time_end - time_start
print finishTime
4

1 回答 1

3

等效的python代码是这样的:

needle = open("needle.wav", "rb").read()[46:]

for x in range(0, 10000):
    haystack = open("haystack.wav", "rb").read()
    match = haystack.index(needle)
于 2013-03-01T14:21:15.207 回答