Я создаю сетку меток, цвета фона которой затем можно постоянно менять по мере изменения значений местоположения сетки. У меня есть два разных способа получить метку в определенном месте сетки, а затем изменить ее цвет (ChangeBox1 и ChangeBox2).
Когда я вызываю эти подпрограммы в функции инициализации класса, они выполняются значительно быстрее, чем когда я вызываю их после отображения окна.
Почему?
Я использую Python 3.10.15
Average execution time of ChangeBox1 in init over 500 runs: 9.419159032404423e-07 seconds
Average execution time of ChangeBox2 in init over 500 runs: 4.6449992805719374e-07 seconds
Average execution time of ChangeBox1 after window.show over 500 runs: 1.5272999880835415e-05 seconds
Average execution time of ChangeBox2 after window.show over 500 runs: 1.4401915948837996e-05 seconds
Вот мой MWE:
import timeit
from PySide6.QtCore import QSize, Qt
from PySide6.QtGui import QColor
from PySide6.QtWidgets import (
QApplication,
QGridLayout,
QLabel,
QMainWindow,
QWidget,
)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
self.setMinimumSize(QSize(400, 300))
self.layout = QGridLayout()
self.layout.setSpacing(3)
xMax = 4
yMax = 5
steps = xMax * yMax
midStep = steps // 2 + 1
cStep = 255 // midStep
cRed = 255
cGreen = 0
cBlue = 0
self.labels = {}
for b in range(steps):
label = f"T{b}"
(x, y) = divmod(b, yMax)
color = f"{cRed:02x}{cGreen:02x}{cBlue:02x}"
self.labels[(x, y)] = self.AddBox(color, label, x, y)
if b < midStep:
cGreen += cStep
else:
cRed -= cStep
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
runs = 500
time1 = timeit.timeit(lambda: self.ChangeBox1(2, 2), number=runs)
time2 = timeit.timeit(lambda: self.ChangeBox2(1, 1), number=runs)
print(
f"Average execution time of ChangeBox1 in init over {runs} runs: {time1 / runs} seconds"
)
print(
f"Average execution time of ChangeBox2 in init over {runs} runs: {time2 / runs} seconds"
)
# Find the fastest way to change the color of a specific widget
def ChangeBoxColor(self):
self.ChangeBox1(2, 2)
self.ChangeBox2(1, 1)
runs = 500
time1 = timeit.timeit(lambda: self.ChangeBox1(2, 2), number=runs)
time2 = timeit.timeit(lambda: self.ChangeBox2(1, 1), number=runs)
print(
f"Average execution time of ChangeBox1 after window.show over {runs} runs: {time1 / runs} seconds"
)
print(
f"Average execution time of ChangeBox2 after window.show over {runs} runs: {time2 / runs} seconds"
)
def MyLabel(self, color, text):
tBox = QLabel(text)
tBox.setAlignment(Qt.AlignCenter)
tBox.setStyleSheet(f"background: #{color}; font-style: bold; font-size: 24pt")
return tBox
def AddBox(self, color, text, x, y):
box = self.MyLabel(color, text)
self.layout.addWidget(box, x, y)
return box
def ChangeBox1(self, x, y):
cell = self.layout.itemAtPosition(x, y).widget()
cell.setStyleSheet(
f"background: #{'0000ff'}; font-style: bold; font-size: 24pt"
)
def ChangeBox2(self, x, y):
self.labels[(x, y)].setStyleSheet(
f"background: #{'00f0ff'}; font-style: bold; font-size: 24pt"
)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
window.ChangeBoxColor()
app.exec()
Подробнее здесь: https://stackoverflow.com/questions/798 ... ifferences
PySide6 Разница во времени ⇐ Python
Программы на Python
1767297696
Anonymous
Я создаю сетку меток, цвета фона которой затем можно постоянно менять по мере изменения значений местоположения сетки. У меня есть два разных способа получить метку в определенном месте сетки, а затем изменить ее цвет (ChangeBox1 и ChangeBox2).
Когда я вызываю эти подпрограммы в функции инициализации класса, они выполняются значительно быстрее, чем когда я вызываю их после отображения окна.
Почему?
Я использую Python 3.10.15
Average execution time of ChangeBox1 in init over 500 runs: 9.419159032404423e-07 seconds
Average execution time of ChangeBox2 in init over 500 runs: 4.6449992805719374e-07 seconds
Average execution time of ChangeBox1 after window.show over 500 runs: 1.5272999880835415e-05 seconds
Average execution time of ChangeBox2 after window.show over 500 runs: 1.4401915948837996e-05 seconds
Вот мой MWE:
import timeit
from PySide6.QtCore import QSize, Qt
from PySide6.QtGui import QColor
from PySide6.QtWidgets import (
QApplication,
QGridLayout,
QLabel,
QMainWindow,
QWidget,
)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
self.setMinimumSize(QSize(400, 300))
self.layout = QGridLayout()
self.layout.setSpacing(3)
xMax = 4
yMax = 5
steps = xMax * yMax
midStep = steps // 2 + 1
cStep = 255 // midStep
cRed = 255
cGreen = 0
cBlue = 0
self.labels = {}
for b in range(steps):
label = f"T{b}"
(x, y) = divmod(b, yMax)
color = f"{cRed:02x}{cGreen:02x}{cBlue:02x}"
self.labels[(x, y)] = self.AddBox(color, label, x, y)
if b < midStep:
cGreen += cStep
else:
cRed -= cStep
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
runs = 500
time1 = timeit.timeit(lambda: self.ChangeBox1(2, 2), number=runs)
time2 = timeit.timeit(lambda: self.ChangeBox2(1, 1), number=runs)
print(
f"Average execution time of ChangeBox1 in init over {runs} runs: {time1 / runs} seconds"
)
print(
f"Average execution time of ChangeBox2 in init over {runs} runs: {time2 / runs} seconds"
)
# Find the fastest way to change the color of a specific widget
def ChangeBoxColor(self):
self.ChangeBox1(2, 2)
self.ChangeBox2(1, 1)
runs = 500
time1 = timeit.timeit(lambda: self.ChangeBox1(2, 2), number=runs)
time2 = timeit.timeit(lambda: self.ChangeBox2(1, 1), number=runs)
print(
f"Average execution time of ChangeBox1 after window.show over {runs} runs: {time1 / runs} seconds"
)
print(
f"Average execution time of ChangeBox2 after window.show over {runs} runs: {time2 / runs} seconds"
)
def MyLabel(self, color, text):
tBox = QLabel(text)
tBox.setAlignment(Qt.AlignCenter)
tBox.setStyleSheet(f"background: #{color}; font-style: bold; font-size: 24pt")
return tBox
def AddBox(self, color, text, x, y):
box = self.MyLabel(color, text)
self.layout.addWidget(box, x, y)
return box
def ChangeBox1(self, x, y):
cell = self.layout.itemAtPosition(x, y).widget()
cell.setStyleSheet(
f"background: #{'0000ff'}; font-style: bold; font-size: 24pt"
)
def ChangeBox2(self, x, y):
self.labels[(x, y)].setStyleSheet(
f"background: #{'00f0ff'}; font-style: bold; font-size: 24pt"
)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
window.ChangeBoxColor()
app.exec()
Подробнее здесь: [url]https://stackoverflow.com/questions/79858762/pyside6-timing-differences[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия