def profline(statement, functions): from line_profiler import LineProfiler try: len(functions) except TypeError: lp = LineProfiler(functions) else: lp = LineProfiler(*functions) lp.run(statement) lp.print_stats()
except: pass # print data.iloc[0:num, i] frame = pd.DataFrame.from_items(d, orient="index", columns=["Median (0.25)", "Error (%)", "Median (0.05)", "Error (%)", "Truth"]) print(frame.to_latex(float_format=(lambda x: u"%1.1f" % x))) if args.time: test_median() if args.size: size_vs_error() if args.quality: no_test_DP_median() if args.cprof: import cProfile cProfile.run("test_median()", sort="tottime") if args.lprof: from line_profiler import LineProfiler profile = LineProfiler(test_median, CountSketchCt.estimate, CountSketchCt.aggregate, Ct.__add__, EcPt.__add__, EcPt.__neg__, EcPt.__copy__,) profile.run("test_median()") profile.print_stats()
from twilio.rest import Client from line_profiler import LineProfiler send_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 短信收发费用0.028$ def send_message(): account_sid = 'ACd615e71b7ad5f4686943f7e716e95b0f' auth_token = 'xxxxx' client = Client(account_sid, auth_token) message = client.messages \ .create( body="Join Earth's mightiest heroes. Like Kevin Bacon.", from_='+12187890888', to='+8613871115289' ) print('发送时间:%s \n状态:发送成功!' % send_time) print('接收短信号码:' + message.to) print('短信内容:\n' + message.body) # 打印短信内容 print('短信SID:' + message.sid) # 打印SID #send_message() # 调用执行函数 lptest = LineProfiler(send_message) lptest.run('send_message()') lptest.print_stats()
action='store_true', help='Run the c profiler') parser.add_argument('--plot', action='store_true', help='Upload time plot to plotly') args = parser.parse_args() if args.time: xxx = msg_mass() test_full_client(xxx) if args.cprof: import cProfile xxx = msg_mass() cProfile.run("test_full_client(xxx)", sort="tottime") if args.lprof: from line_profiler import LineProfiler #import rscoin.rscservice profile = LineProfiler(rscoin.rscservice.RSCProtocol.handle_Query, rscoin.rscservice.RSCFactory.process_TxQuery, rscoin.Tx.check_transaction, rscoin.Tx.check_transaction_utxo, rscoin.Tx.parse) xxx = msg_mass() profile.run("test_full_client(xxx)") profile.print_stats()
properties[i].append(objects[j].moments_hu()) properties[i].append(objects[j].image()) properties[i].append(objects[j].label) properties[i].append(objects[j].major_axis_length()) properties[i].append(objects[j].max_intensity()) properties[i].append(objects[j].mean_intensity()) properties[i].append(objects[j].min_intensity()) properties[i].append(objects[j].minor_axis_length()) properties[i].append(objects[j].moments()) properties[i].append(objects[j].moments_normalized()) properties[i].append(objects[j].orientation()) properties[i].append(objects[j].perimeter()) properties[i].append(objects[j].solidity()) properties[i].append(objects[j].weighted_moments_central()) properties[i].append(objects[j].weighted_centroid()) properties[i].append(objects[j].weighted_moments_hu()) properties[i].append(objects[j].weighted_moments()) properties[i].append(objects[j].weighted_moments_normalized()) return properties, prop_names if __name__ == '__main__': image = io.imread('test-image.png') green = image[..., 1].copy() lp = LineProfiler() lp.add_function(object_features) lp.run('intensity_object_features(green, 100)') lp.print_stats() lp.dump_stats('profile.lprof') print(__file__)
import app from line_profiler import LineProfiler import numpy as np import time from tqdm import tqdm import matplotlib.pyplot as plt profile = LineProfiler() profile.add_module(app) profile.run("app.Application()") profile.print_stats()
args = parser.parse_args() if args.time: notest_timing(31) if args.cprof: import cProfile cProfile.run("notest_timing(51)", sort="tottime") if args.lprof: from line_profiler import LineProfiler profile = LineProfiler(VerifyOneOfN, ProveOneOfN, Bn.__init__, Bn.__del__) profile.run("notest_timing(31)") profile.print_stats() if args.plot: all_sizes, prove_time, verify_time = notest_timing() import plotly.plotly as py from plotly.graph_objs import * trace0 = Scatter( x=all_sizes, y=prove_time, name='Proving', ) trace1 = Scatter(
from line_profiler import LineProfiler from sklearn_seco import SimpleSeCoEstimator from sklearn_seco.common import match_rule, RuleContext from sklearn_seco.tests import conftest def tcn2(dataset): with warnings.catch_warnings(): from _pytest.deprecated import RemovedInPytest4Warning warnings.simplefilter("ignore", RemovedInPytest4Warning) est = SimpleSeCoEstimator() est.fit(dataset.x_train, dataset.y_train) ypred = est.predict(dataset.x_test) from sklearn.metrics import classification_report, confusion_matrix print(confusion_matrix(dataset.y_test, ypred)) print(classification_report(dataset.y_test, ypred)) try: from numba import NumbaWarning warnings.simplefilter("error", NumbaWarning) except ImportError: pass profile = LineProfiler() profile.add_function(match_rule) profile.add_function(RuleContext._count_matches) profile.add_function(RuleContext.pn) profile.run('tcn2(conftest.sklearn_make_moons())') profile.print_stats()
if stats[l][j]['case'] == 'L' and stats[k][i]['case'] == 'U': continue if stats[l][j]['alph'] == 'A' and stats[k][i]['alph'] == 'N': continue if stats[l][j]['alph'] == 'N' and stats[k][i]['alph'] == 'A': continue y = tabs[l][j] if len(y) < 3: continue # avoid boolean # common types comtyp = typsets[k][i] & typsets[l][j] # if len(comtyp) == 0: continue # not good, miss most refs # if y <= x: # (strict) subset # instead: 90% subset fracsubs = fracsubset(y, x) if fracsubs >= 0.9: # table l, column j is subset of table k, column i: table l references table k ? fout.write("insert into sub (l, j, k, i, comtyp, fracsubset, nchild, nparent, fnchild, fnparent)" + " values (%d, %d, %d, %d, '%s', %f, %d, %d, '%s', '%s');\n" % (l, j, k, i, len(comtyp), fracsubs, len(y), len(x), cleanfn(sam[l]), cleanfn(sam[k]))) fout.write("commit;\n") fout.close() t3 = time() print('references done in %.1f seconds' % (t3-t2,), file=sys.stderr) print('total run time %.1f seconds or %.1f minutes' % (t3-t0, (t3-t0)/60), file=sys.stderr) sys.exit(0) if '--profile' in sys.argv: print('profiling..', file=sys.stderr) prof = LineProfiler(main) prof.run('main()') prof.print_stats() else: main()
""" Line-by-line profiling of CPU use of Python scripts in :mod:`mandelbrot.implementations` using :mod:`line_profiler`. """ from line_profiler import LineProfiler import mandelbrot if __name__ == "__main__": args = mandelbrot.parsed_mandelbrot_args() for impl in mandelbrot.all_implementations(): print(f"About to profile {impl.id_}") profile = LineProfiler() profile.add_function(impl.callable) cmd = ( f"{impl.fully_qualified_name}(grid_side_size={args.grid_side_size}, " f"max_iter={args.max_iter})" ) profile.run(cmd) profile.print_stats()
# !/usr/bin/env python # -*- coding: utf-8 -*- from line_profiler import LineProfiler """ 分析时间耗时, 这个包需要下载到本地进行安装: pip3 install ./python_module/memory_profiler_module/line_profiler-3.1.0-cp37-cp37m-win_amd64.whl """ def operation1(): num = 0 for i in range(10000): num += 1 def operation2(): num = 0 while (num < 10000): num += 1 if __name__ == "__main__": lprofiler = LineProfiler(operation1, operation2) lprofiler.run('operation1()') lprofiler.run('operation2()') lprofiler.print_stats()
args = parser.parse_args() if args.time: notest_timing(31) if args.cprof: import cProfile cProfile.run("notest_timing(51)", sort="tottime") if args.lprof: from line_profiler import LineProfiler profile = LineProfiler(VerifyOneOfN, ProveOneOfN, Bn.__init__, Bn.__del__) profile.run("notest_timing(31)") profile.print_stats() if args.plot: all_sizes, prove_time, verify_time = notest_timing() import plotly.plotly as py from plotly.graph_objs import * trace0 = Scatter( x=all_sizes, y=prove_time, name='Proving', )
# has 3 expensive lines - check_array, np.asarray, np.average #https://github.com/scikit-learn/scikit-learn/blob/1495f69242646d239d89a5713982946b8ffcf9d9/sklearn/utils/validation.py#L600 # check_X_y # checks for array for certain characteristics and lengths # df = pd.read_pickle('generated_ols_data.pickle') print(f"Loaded {df.shape} rows") est = LinearRegression() row = df.iloc[0] X = np.arange(row.shape[0]).reshape(-1, 1).astype(np.float_) lp = LineProfiler(est.fit) print("Run on a single row") lp.run("est.fit(X, row.values)") lp.print_stats() print("Run on 5000 rows") lp.run("df[:5000].apply(ols_sklearn, axis=1)") lp.print_stats() lp = LineProfiler(base._preprocess_data) lp.run("base._preprocess_data(X, row, fit_intercept=True)") lp.print_stats() lp = LineProfiler(base.check_X_y) lp.run( "base.check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'], y_numeric=True, multi_output=True)" ) lp.print_stats()
parser.add_argument('--plot', action='store_true', help='Upload time plot to plotly') args = parser.parse_args() if args.time: xxx = msg_mass() test_full_client(xxx) if args.cprof: import cProfile xxx = msg_mass() cProfile.run("test_full_client(xxx)", sort="tottime") if args.lprof: from line_profiler import LineProfiler #import rscoin.rscservice profile = LineProfiler(rscoin.rscservice.RSCProtocol.handle_Query, rscoin.rscservice.RSCFactory.process_TxQuery, rscoin.Tx.check_transaction, rscoin.Tx.check_transaction_utxo, rscoin.Tx.parse) xxx = msg_mass() profile.run("test_full_client(xxx)") profile.print_stats()
for timestamp in bit_2_events[-5:]: print "unstrobed bit 2 t=%f" % timestamp print "found %d bit 3 events. Last 5 events are:" %(len(bit_3_events)) for timestamp in bit_3_events[-5:]: print "unstrobed bit 3 t=%f" % timestamp unstrobed_word = pu.GetExtEvents(data, event='unstrobed_word', online=False) print "found %d unstrobed word events in which 10 events are:" %(len(unstrobed_word['value'])) indices = np.arange(0,len(unstrobed_word['value']),len(unstrobed_word['value'])/10) for value,timestamp in zip(unstrobed_word['value'][indices],unstrobed_word['timestamp'][indices]) : binary_value = bin(value) print "unstrobed word:%s t=%f" % (binary_value,timestamp) if __name__ == "__main__": #run() profile = LineProfiler() profile.add_function(run) profile.add_function(PlexUtil.GetExtEvents) profile.add_function(reconstruct_word) profile.run('run()') profile.print_stats() profile.dump_stats("testPlexFile_profile.lprof") #cProfile.run('run()','PlexFile_profile') #p = pstats.Stats('testPlexFile_profile.lprof') #p.sort_stats('cumulative') #p.print_stats() #print h.heap()
# Test and profile TimeHistogram # # Copyright (C) 2010-2012 Huang Xin # # See LICENSE.TXT that came with this file. #import cProfile,pstats from line_profiler import LineProfiler import TimeHistogram def run(): psth = TimeHistogram.PSTHAverage( '/home/chrox/dev/plexon_data/c04-stim-timing-8ms-rand-1.plx') psth.get_data() if __name__ == '__main__': #cProfile.run('psth.get_data()','hist_profile') #p = pstats.Stats('hist_profile') #p.sort_stats('cumulative') #p.print_stats() profile = LineProfiler() profile.add_function(run) profile.add_function(TimeHistogram.PSTHAverage._process_unit) profile.run('run()') profile.print_stats() profile.dump_stats("hist_profile.lprof")
# ============================================================================= # ============================================================================= # Functions # ============================================================================= # ============================================================================= # Init # ============================================================================= if __name__ == '__main__': profiler = LineProfiler() #profiler.add_function(translations.TranslationFile.get_translation) #profiler.add_function(translations.TranslationFile._read) profiler.add_function(translations.TranslationString._set_string) #profiler.add_function(translations.Translation.get_language) #profiler.add_function(translations.TranslationQuantifier.handle) #profiler.add_function(translations.TranslationRange.in_range) #profiler.add_function(translations.TranslationLanguage.get_string) profiler.run( "s = translations.TranslationFile('C:/Temp/MetaData/stat_descriptions.txt')" ) profiler.run( "for i in range(0, 100): t = s.get_translation(tags=['additional_chance_to_take_critical_strike_%', 'additional_chance_to_take_critical_strike_%'], values=((3, 5), 6))" ) profiler.print_stats() print('translations.Translation:', t)