本文整理汇总了Python中timeit.timeit函数的典型用法代码示例。如果您正苦于以下问题:Python timeit函数的具体用法?Python timeit怎么用?Python timeit使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了timeit函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_speedup_factor
def get_speedup_factor(self, baseline_fcn, optimized_fcn, num_tests):
baseline_performance = timeit.timeit(baseline_fcn, number=num_tests)
optimized_performance = timeit.timeit(optimized_fcn, number=num_tests)
_message = "Performance test too fast, susceptible to overhead"
T.assert_gt(baseline_performance, 0.005, _message)
T.assert_gt(optimized_performance, 0.005, _message)
return (baseline_performance / optimized_performance)
示例2: run
def run(self):
"""Perform the oct2py speed analysis.
Uses timeit to test the raw execution of an Octave command,
Then tests progressively larger array passing.
"""
print('oct2py speed test')
print('*' * 20)
time.sleep(1)
print('Raw speed: ')
avg = timeit.timeit(self.raw_speed, number=200) / 200
print(' {0:0.01f} usec per loop'.format(avg * 1e6))
sides = [1, 10, 100, 1000]
runs = [200, 200, 100, 10]
for (side, nruns) in zip(sides, runs):
self.array = np.reshape(np.arange(side ** 2), (-1))
print('Put {0}x{1}: '.format(side, side))
avg = timeit.timeit(self.large_array_put, number=nruns) / nruns
print(' {0:0.01f} msec'.format(avg * 1e3))
print('Get {0}x{1}: '.format(side, side))
avg = timeit.timeit(self.large_array_get, number=nruns) / nruns
print(' {0:0.01f} msec'.format(avg * 1e3))
self.octave.close()
print('*' * 20)
print('Test complete!')
示例3: _fast_crc
def _fast_crc(count=50):
"""
On certain platforms/builds zlib.adler32 is substantially
faster than zlib.crc32, but it is not consistent across
Windows/Linux/OSX.
This function runs a quick check (2ms on my machines) to
determine the fastest hashing function available in zlib.
Parameters
------------
count: int, number of repetitions to do on the speed trial
Returns
----------
crc32: function, either zlib.adler32 or zlib.crc32
"""
import timeit
setup = 'import numpy, zlib;'
setup += 'd = numpy.random.random((500,3));'
crc32 = timeit.timeit(setup=setup,
stmt='zlib.crc32(d)',
number=count)
adler32 = timeit.timeit(setup=setup,
stmt='zlib.adler32(d)',
number=count)
if adler32 < crc32:
return zlib.adler32
else:
return zlib.crc32
示例4: main
def main():
vector = Vector(.333, .555, .2831).normalize()
origin = Vector(138.2, 22.459, 12)
maxDistance = 1000
def cast_py():
return numpy.array(list(_cast(origin, vector, maxDistance, 1)))
def cast_np():
return _cast_np(origin, vector, maxDistance, 1)
res_py = cast_py()
res_np = cast_np()
print("res_py", res_py.shape)
print("res_np", res_np.shape)
s = min(len(res_py), len(res_np))
passed = (res_py[:s] == res_np[:s]).all()
print("Passed" if passed else "Failed")
from timeit import timeit
t_py = timeit(cast_py, number=1)
t_np = timeit(cast_np, number=1)
print("Time cast_py", t_py)
print("Time cast_np", t_np)
示例5: main
def main():
monitorDevice=deviceMonitor.MonitorDevices('monitorDevice')
print '\n'
print "Start conn test"
deviceConn=timeit.timeit('MonitorDevices.deviceConnectivity', setup='from deviceMonitor import MonitorDevices', number=1000)
print 'Time to execute dev conn: %s ' % deviceConn
print monitorDevice.deviceConnectivity()
print '\n'
print "Start devRunState test"
deviceRunning=timeit.timeit('MonitorDevices.deviceRunning', setup='from deviceMonitor import MonitorDevices', number=1000)
print 'Time to execute dev run state: %s ' % deviceRunning
print monitorDevice.deviceRunning()
print '\n'
devicePollInterval=timeit.timeit('MonitorDevices.devicePollInterval', setup='from deviceMonitor import MonitorDevices', number=1000)
print 'Time to execute dev poll interval: %s ' % devicePollInterval
print monitorDevice.devicePollInterval()
示例6: graph_creation_static_vs_dynamic_rnn_benchmark
def graph_creation_static_vs_dynamic_rnn_benchmark(max_time):
config = tf.ConfigProto()
config.allow_soft_placement = True
# These parameters don't matter
batch_size = 512
num_units = 512
# Set up sequence lengths
np.random.seed([127])
sequence_length = np.random.randint(0, max_time, size=batch_size)
inputs_list = [np.random.randn(batch_size, num_units).astype(np.float32) for _ in range(max_time)]
inputs = np.dstack(inputs_list).transpose([0, 2, 1]) # batch x time x depth
def _create_static_rnn():
with tf.Session(config=config, graph=tf.Graph()) as sess:
inputs_list_t = [tf.constant(x) for x in inputs_list]
ops = _static_vs_dynamic_rnn_benchmark_static(inputs_list_t, sequence_length)
def _create_dynamic_rnn():
with tf.Session(config=config, graph=tf.Graph()) as sess:
inputs_t = tf.constant(inputs)
ops = _static_vs_dynamic_rnn_benchmark_dynamic(inputs_t, sequence_length)
delta_static = timeit.timeit(_create_static_rnn, number=5)
delta_dynamic = timeit.timeit(_create_dynamic_rnn, number=5)
print("%d \t %f \t %f \t %f" % (max_time, delta_static, delta_dynamic, delta_dynamic / delta_static))
示例7: test_speed_of_reading_fcs_files
def test_speed_of_reading_fcs_files(self):
""" Testing the speed of loading a FCS files"""
fname = file_formats["mq fcs 3.1"]
number = 1000
print
time = timeit.timeit(
lambda: parse_fcs(fname, meta_data_only=True, output_format="DataFrame", reformat_meta=False), number=number
)
print "Loading fcs file {0} times with meta_data only without reformatting of meta takes {1} per loop".format(
time / number, number
)
time = timeit.timeit(
lambda: parse_fcs(fname, meta_data_only=True, output_format="DataFrame", reformat_meta=True), number=number
)
print "Loading fcs file {0} times with meta_data only with reformatting of meta takes {1} per loop".format(
time / number, number
)
time = timeit.timeit(
lambda: parse_fcs(fname, meta_data_only=False, output_format="DataFrame", reformat_meta=False),
number=number,
)
print "Loading fcs file {0} times both meta and data but without reformatting of meta takes {1} per loop".format(
time / number, number
)
示例8: main
def main():
global str1,str2
n=5000
str1=''.join([random.choice(string.ascii_letters) for i in range(n)])
str2=''.join([random.choice(string.ascii_letters) for i in range(n)])
#print timeit.timeit("lcs1(n,n)",setup="from __main__ import lcs1; n=500",number=1)
print timeit.timeit("lcs2(n,n)",setup="from __main__ import lcs2; n=5000",number=1)
示例9: compareCompleteVSIncomplete
def compareCompleteVSIncomplete():
size = 100
nbOfPoints = 50
nbValuesForAverage = 4
x, yComplete, yIncomplete = [], [], []
for i in numpy.linspace(0, size*(size-1), nbOfPoints):
# Computes matrix density
x.append((size*size-i)/(size*size))
# Computes average execution times on 3 calls on different matrix
completeTime, incompleteTime = 0, 0
for j in range(nbValuesForAverage):
M = matgen.symmetricSparsePositiveDefinite(size, i)
wrapped1 = wrapper(cholesky.completeCholesky, M)
completeTime += timeit.timeit(wrapped1, number=1)
wrapped2 = wrapper(cholesky.incompleteCholesky, M)
incompleteTime += timeit.timeit(wrapped2, number=1)
yComplete.append(completeTime/nbValuesForAverage)
yIncomplete.append(incompleteTime/nbValuesForAverage)
p1 = plt.plot(x, yComplete, 'b', marker='o')
p2 = plt.plot(x, yIncomplete, 'g', marker='o')
plt.title("Average execution time for the Cholesky factorization in function of matrix density\n")
plt.legend(["New custom Complete factorization", "Custom incomplete factorization"], loc=4)
plt.ylabel("Execution time (s)")
plt.xlabel("density of the initial 100*100 matrix")
plt.show()
示例10: readPWM
def readPWM(pinNum):
startpwm = timeit.timeit() # Time the pwm for now
highCount = 0
totCount = 0
cur = GPIO.input(pinNum)
while True:
prev = cur
cur = GPIO.input(pinNum)
if ( cur == 1 ): # The gpio pin is high, increment high count
highCount += 1
totCount += 1
elif ( prev == 1 and cur == 0 ): # Period has ended, now determine DC.
totCount += 1
dutyCycle = highCount/totCount
break
else:
totCount += 1
#End if
#End while
endpwm = timeit.timeit()
totalTime = abs(1000*(endpwm - startpwm)) # Convert sec to ms
print 'PWM took %.3f microseconds.' %(totalTime)
return dutyCycle
示例11: runLibraryTests
def runLibraryTests(self,fibLibrary,resultDictionary):
try:
resultDictionary[' library'] = fibLibrary
startTime = time.clock()
methodLoad = __import__(fibLibrary)
dynLoad = 'methodLoad.'+fibLibrary+'()'
fibLib = eval(dynLoad)
resultDictionary['sequence 10'] = fibLib.fibList(10)
resultDictionary['sequence 50'] = fibLib.fibList(50)
resultDictionary['sequence 100'] = fibLib.fibList(100)
resultDictionary['sequence 500'] = fibLib.fibList(500)
resultDictionary['starts at 0'] = fibLib.fibAtN(0)
resultDictionary['value at 5'] = fibLib.fibAtN(5)
resultDictionary['value at 200'] = fibLib.fibAtN(200)
resultDictionary['floor of 1000'] = fibLib.fibFloor(1000)
resultDictionary['ceil of 1000'] = fibLib.fibCeil(1000)
ss = "fib=__import__('"+fibLibrary+"'); fibLib=fib."+fibLibrary+'()'
resultDictionary['sequence speed tests'] = timeit.timeit('fibLib.fibList(311)', setup=ss ,number = 5000)
resultDictionary['value speed tests']=timeit.timeit('fibLib.fibAtN(311)', setup=ss, number = 5000)
resultDictionary['floor speed tests']=timeit.timeit('fibLib.fibFloor(311)', setup=ss, number = 5000)
resultDictionary['ceiling speed tests']=timeit.timeit('fibLib.fibCeil(311)', setup=ss, number = 5000)
stopTime = time.clock()
resultDictionary['time of basic tests'] = stopTime - startTime
except:
return('exception')
else:
return('tests worked')
示例12: rxcui_unit_tests
def rxcui_unit_tests(unii, chembl_id, chebi_id, wikidata_accession):
unii_com = gnomics.objects.compound.Compound(identifier = str(unii), identifier_type = "UNII", source = "FDA")
print("\nGetting drugs (RxCUIs) from compound (UNII) (%s):" % unii)
for rx in get_drugs(unii_com):
for iden in rx.identifiers:
print("- %s (%s)" % (str(iden["identifier"]), iden["identifier_type"]))
chembl_com = gnomics.objects.compound.Compound(identifier = str(chembl_id), identifier_type = "ChEMBL ID", source = "ChEMBL")
print("\nGetting drug identifiers from compound (ChEMBL ID) (%s):" % chembl_id)
for rx in get_drugs(chembl_com):
for iden in rx.identifiers:
print("- %s (%s)" % (str(iden["identifier"]), iden["identifier_type"]))
chebi_com = gnomics.objects.compound.Compound(identifier = str(chebi_id), identifier_type = "ChEBI ID", source = "ChEBI")
print("\nGetting drug identifiers from compound (ChEBI ID) (%s):" % chebi_id)
for rx in get_drugs(chebi_com):
for iden in rx.identifiers:
print("- %s (%s)" % (str(iden["identifier"]), iden["identifier_type"]))
wikidata_com = gnomics.objects.compound.Compound(identifier = str(wikidata_accession), identifier_type = "Wikidata Accession", source = "Wikidata")
print("\nGetting drug identifiers from Wikidata Accession (%s):" % wikidata_accession)
start = timeit.timeit()
all_drugs = get_drugs(wikidata_com)
end = timeit.timeit()
print("TIME ELAPSED: %s seconds." % str(end - start))
for rx in all_drugs:
for iden in rx.identifiers:
print("- %s (%s)" % (str(iden["identifier"]), iden["identifier_type"]))
示例13: diff
def diff(self, iterN=100):
baseSetup = self.baseSetup + '; bcg=np.random.rand(640, 480)'
cv2Cmd = 'test=cv2.absdiff(bcg, data)'
numpyCmd = 'test=data - bcg'
print timeit.timeit(setup=baseSetup, stmt=numpyCmd, number=iterN)/iterN
print timeit.timeit(setup=baseSetup, stmt=cv2Cmd, number=iterN)/iterN
示例14: patent_unit_tests
def patent_unit_tests(chebi_id, pubchem_cid, pubchem_sid, kegg_compound_id):
chebi_com = gnomics.objects.compound.Compound(identifier = str(chebi_id), identifier_type = "ChEBI ID", source = "ChEBI")
print("Getting patent accessions from ChEBI ID (%s):" % chebi_id)
for acc in get_patents(chebi_com):
for iden in acc.identifiers:
print("- %s" % str(iden["identifier"]))
pubchem_com = gnomics.objects.compound.Compound(identifier = str(pubchem_cid), identifier_type = "PubChem CID", source = "PubChem")
print("\nGetting patent accessions from PubChem CID (%s):" % pubchem_cid)
for acc in get_patents(pubchem_com):
for iden in acc.identifiers:
print("- %s" % str(iden["identifier"]))
pubchem_sub = gnomics.objects.compound.Compound(identifier = str(pubchem_sid), identifier_type = "PubChem SID", source = "PubChem")
print("\nGetting patent accessions from PubChem SID (%s):" % pubchem_sid)
for acc in get_patents(pubchem_sub):
for iden in acc.identifiers:
print("- %s" % str(iden["identifier"]))
kegg_com = gnomics.objects.compound.Compound(identifier = str(kegg_compound_id), identifier_type = "KEGG Compound ID", source = "KEGG")
print("\nGetting patent accessions from KEGG Compound ID (%s):" % kegg_compound_id)
start = timeit.timeit()
all_patents = get_patents(kegg_com)
end = timeit.timeit()
print("TIME ELAPSED: %s seconds." % str(end - start))
for acc in all_patents:
for iden in acc.identifiers:
print("- %s" % str(iden["identifier"]))
示例15: main
def main():
"""Main"""
# number and length of lines in test file
NUM_LINES = 1000
LINE_LENGTH = 80
# First, generate a test file
with open('test_input.txt', 'w') as fp:
for i in range(NUM_LINES):
fp.write("".join(random.sample(string.ascii_letters * 2,
LINE_LENGTH)) + "\n")
# If STDIN specified, compare performance for parsing STDIN
# Since the stdin buffer does not support seeking, it is not possible
# to use timeit to benchmark this. Instead a single time will be
# provided and it should be rerun from the shell multiple times to
# compare performance
if not sys.stdin.isatty():
# Test 1
#timeit.timeit(s)
#timeit.timeit("peeker_test()", setup='from __main__ import peeker_test')
#builtin_stdin_test()
peeker_stdin_test()
else:
# Otherwise, compare performance for reading files
t = timeit.timeit("builtin_file_test()",
setup='from __main__ import builtin_file_test')
print("Built-in file stream test (1,000,000 reps): %f" % t)
t = timeit.timeit("peeker_file_test()",
setup='from __main__ import Peeker,peeker_file_test')
print("Peeker file stream test (1,000,000 reps): %f" % t)