Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Потрепаться";
Текущий архив: 2002.06.24;
Скачать: [xml.tar.bz2];

Вниз

Про Исходный код   Найти похожие ветки 

 
Демон   (2002-05-21 17:28) [0]

Говорят в С++ можно оптимизировать код программы.
А в Делфях такая фишка есть????


 
ZZ   (2002-05-21 17:31) [1]

Оригинально однако :))

PS. А тебе не сказали, что значит оптимизировать?


 
Демон   (2002-05-21 17:37) [2]

Значит из подключаемых библиотек выкидываются не используемые функции!


 
Johnny Smith   (2002-05-21 17:49) [3]

Да, вопрос, пожалуй, не совсем корректен... Насколько я знаю, из подключаемых библиотек в Дельфях И ТАК выкидываются неиспользуемые функции.
Компилятор Дельфей, помимо прочего, может оптимизить код включением соответствующего чекбокса на закладке Compiler в Project Options.
Что касается С++, то там действительно куча оптимизационных тонкостей в разных компиляторах. Шикарный анализ этих фичей приведен в статье Криса Касперского в апрельском номере "Программиста".


 
ZZ   (2002-05-21 17:57) [4]

Значит из подключаемых библиотек выкидываются не используемые функции! = Из программы выкидываются неиспользуемые функции.

И естественно это в Дельфи есть.


 
Демон   (2002-05-21 18:50) [5]

в с++ при оптимизации файл пости на 50%ь меньше становится
а я в делвях пощелкал флйл всегда одной величины


 
Agent Smith   (2002-05-21 19:12) [6]

Смотря какой компилятор брать за основу. Ну, например Borland C++ Builder. Там вообще шикарная оптимизация. Если в С++В сделать прогу, а потом именно такую же написать на Delphi, то на С размер файла будет чуть ли не в 10 раз меньше! Конечно, можно урезать ехе и в Delphi, отключив кое-какие библиотеки, но тогда на компе, где должна работать эта программа должны быть эти библиотеки. Вот такие дела... А вообще, если охота получить маленький ехе, а синтаксис С++ знаком, то лучше, чем C++ Builder трудно будет что-либо найти. И, кстати, интерфейс там - копия Дельфяшного, как и компоненты, свойства, события и наследие.
К стати, главным плюсом "толстого" кода на Дельфи я считаю усложнение попытки взлома программы. Например, если твоя программа привязывается к материнке, то найти это в машинном коде будет довольно трудно.


 
PVOzerski   (2002-05-21 19:23) [7]

>Смотря какой компилятор брать за основу. Ну, например Borland >C++ Builder. Там вообще шикарная оптимизация. Если в С++В >сделать прогу, а потом именно такую же написать на Delphi, то >на С размер файла будет чуть ли не в 10 раз меньше!
Что-то сомнения меня мучают. Особенно - в свете обсуждавшейся когда-то на Базарной площади Королевства темы: почему на Билдере приложения получаются БОЛЬШЕ. Вы с VCL проги сравнивали или без?
По поводу оптимизации: а ведь она разная бывает. Бывает на размер приложения, а бывает на скорость его исполнения. Но вообще, возможности оптимизации (гибкость) в Билдере куда больше, чем в Дельфи :^(. Зато Delphi DCU делает, пригодные для smart linking (в отличие от OBJ-файлов).


 
Reindeer Moss Eater   (2002-05-21 19:25) [8]

У билдера и Delphi VCL одна и та же, на Object Pascale нарисована


 
PVOzerski   (2002-05-21 19:40) [9]

2 Reindeer Moss Eater
О том и речь. Хотя это чуть-чуть не точно: в Delphi она линкуется как DCU, в Билдере - как OBJ-файлы. Впрочем, из-за особенностей организации классов сильно много мёртвого кода всё равно не выкинуть (если написано в объектно-ориентированном стиле, а это безусловно относится к VCL). Но вот если писать без классов и без VCL, тогда действительно можно было бы сравнить эффективность оптимизации (впрочим, опять же отошлю к Базарной площади Королевства ("Сравнение компиляторов").
Возвращаясь к вопросу: по сути дела, управление оптимизацией в Delphi сводится к директиве компилятора O+/-. Правда, она локальная, поэтому кое-какой гибкости добиться можно. Плюс к этому, иногда полезно поиграть в calling conventions. А в C/C++ для оптимизации - куча разных прагм.


 
Viewer   (2002-05-21 19:49) [10]

Такие "фишки", как оптимизация, есть везде.
Есть, однако управляемые, посредством опций компилятора и есть встроенные в компилятор.
В Дельфи набор опций достаточно минимален.
В Си-компиляторах, как правило, гораздо больше вариантов управления оптимизацией.
Довольно интересны Intel-C и MSVC компиляторы в этом отношении.
А скажем Borland-C гораздо более строг.

Впрочем, для Паскаля, есть например, FreePascal, где также изобилие опций.
Вообще вопрос оптимизации исполнения скомпилированного файла, как верно заметил PVOzerski - вопрос неоднозначный.
Есть много вариантов этой самой оптимизации.
Собственно, что есть оптимальность ?
Это достижение максимума или минимума некоторой целевой функции,
зависящей от двух или более параметров.

Вот, для примера опции управления компиляцией довольно старого, но классного Watcom-компилятора.


 
Viewer   (2002-05-21 19:49) [11]

WATCOM C/C++32 Compile and Link Utility Version 10.0
Copyright by WATCOM International Corp. 1988, 1994. All rights reserved.
WATCOM is a trademark of WATCOM International Corp.
Usage: wcl386 {option(s)} {file(s)}
Options: ( - option is also accepted )
/c compile only, no link /y ignore the WCL386 environment variable
/cc treat source files as C code /cc++ treat source files as C++ code
[Preprocessor options]
/d<name>[=text] define a macro /p preprocess file
/d+ extend syntax of /d option /pl output #line directives
/fo=<filename> set object file name /pc output comments
/i=<directory> include directory /plc output #line and comments
/u<name> undefine macro name
Press any key to continue:
[Compiler options]
/3r 386 register calling conventions /nm=<module_name> set module name
/3s 386 stack calling conventions /nt=<name> set text segment name
/4r 486 register calling conventions /r save/restore segregs across calls
/4s 486 stack calling conventions /s remove stack overflow checks
/5r Pentium register calling conv. /v output func declarations to .def
/5s Pentium stack calling conventions /w<number> set warning level number
/d1{+} line number debugging info. /we treat all warnings as errors
/d2 full symbolic debugging info. /z{a,e} disable/enable extensions
/e<number> set error limit number /zc place strings in CODE segment
/ee call epilogue hook routine /zd{f,p} DS floats vs DS pegged to DGROUP
/ei force enums to be type int /zf{f,p} FS floats vs FS pegged to seg
/en emit routine names in the code /zg{f,p} GS floats vs GS pegged to seg
/ep[=<num>] call prologue hook routine/zg generate function prototypes
/ez generate PharLap EZ-OMF object /zk{0,0u,1,2} double-byte char support
/fh=<filename> pre-compiled headers /zku=<codepage> UNICODE support
/fi=<filename> force include of file /zl remove default library information
/fo=<filename> set object file name /zld remove file dependency information
/g=<codegroup> set code group name /zm place functions in separate segments
/hc codeview debug format /zp{1,2,4,8} set struct packing alignment
/hd dwarf debug format /zq operate quietly
/hw watcom debug format /zs check syntax only
/j change char default to signed /zt<number> set data threshold
/m{f,s,m,c,l} memory model /zu SS != DGROUP
/nc=<name> set CODE class name /zw Microsoft Windows
/nd=<name> set data segment name
Press any key to continue:
[Optimization options]
/oa relax alias checking /on generate agressive floating-point
/oc disable call/ret optimization /oo continue compiling when low on memory
/od disable optimizations /op improve floating-point consistency
/oe{=num} expand functions inline /or re-order instructions to avoid stalls
/of{+} generate traceable stack frames/os optimize for space
/oi inline intrinsic functions /ot optimize for time
/ol perform loop optimizations /ou ensure unique addresses for functions
/om generate inline math functions /ox maximum optimization (/oilr /s)
[Floating-point options]
/fpc calls to floating-point library /fpi87 inline 387 instructions
/fpi inline 8087 with emulation /fp2 inline 287 instructions
/fpr use old floating-point convention/fp3 inline 387 instructions
/7 same as /fpi87 /fp5 generate Pentium optimized code
[Linker options]
/bd build Dynamic link library /fm[=<map_file>] generate map file
/bm build Multi-thread application /k<stack_size> set stack size
/bw build default Windowing app. /l=<system> link for the specified system
/bt=<os> build target OS. /x make names case sensitive
/fd[=<directive_file>] directive file @<directive_file> include file
/fe=<executable> name executable file /"linker directives"


 
Viewer   (2002-05-21 19:54) [12]

Собственно опции оптимизации выделены в [Optimization options]
Но кто сказал, что другие опции не влияют на достижение Вами
заданных или желаемых параметров ?


 
Viewer   (2002-05-21 19:56) [13]

А вот если захочется Вам потрудиться вместе с Intel-С, то милости просим:

/O1 optimize for maximum speed, but disable some optimizations which
increase code size for a small speed benefit: /Gfsy /Ob1gysi-
/O2 optimize for maximum speed (DEFAULT): /Gfsy /Ob1gyti
/O3 optimize for maximum speed and enable high-level optimizations
/Ox enable maximum optimizations: /Gs /Ob1gyti (same as /O2 without /Gfy)
/Od disable optimizations; useful for selective optimizations (i.e. /Od /Og)

/Ob<n> control inline expansion:
n=0 disables inlining
n=1 inline functions declared with __inline, and perform C++ inlining
n=2 inline any function, at the compiler"s discretion (same as /Qip)
/Og enable global optimizations
/Oi[-] enable/disable inline expansion of intrinsic functions
/Op[-] enable/disable better floating-point precision
/Os enable speed optimizations, but disable some optimizations which
increase code size for small speed benefit (overrides /Ot)
/Ot enable speed optimizations (overrides /Os)
/Oy[-] enable/disable using EBP as general purpose register (no frame pointer)
/Oa[-] assume no aliasing in program
/Ow[-] assume no aliasing within functions, but assume aliasing across calls

/G5 optimize for Pentium(R) processor
/G6 optimize for Pentium(R) Pro, Pentium(R) II, and Pentium(R) III processors
/G7 optimize for Pentium(R) 4 processor
/GB same as /G6
/Qax<codes> generate code specialized for processor extensions specified by
<codes> while also generating generic IA-32 code. <codes> includes
one or more of the following characters:
i Pentium Pro and Pentium II processor instructions
M MMX(TM) instructions
K streaming SIMD extensions
W Pentium(R) 4 New Instructions
/Qx<codes> generate specialized code to run exclusively on processors
supporting the extensions indicated by <codes> as described above.

/GR[-] enable/disable C++ RTTI
/GX[-] enable/disable C++ exception handling (/GX is same as /EHsc)
/EHa enable asynchronous C++ exception handling model
/EHs enable synchronous C++ exception handling model
/EHc assume extern "C" functions do not throw exceptions

/Gd make __cdecl the default calling convention
/Gr make __fastcall the default calling convention
/Gz make __stdcall the default calling convention

/Ge enable stack checks for all functions
/Gs[n] disable stack checks for functions with less than n bytes of locals
/Gf enable string pooling optimization
/GF enable read-only string pooling optimization
/Gy separate functions for the linker (COMDAT)
/GA optimize for Windows application (assume single-threaded app)
/GT enable fiber-safe thread local storage




 
Viewer   (2002-05-21 19:57) [14]

Advanced Performance
--------------------
Enable and specify the scope of Interprocedural (IP) Optimizations:
/Qip enable single-file IP optimizations (within files, same as /Ob2)
/Qipo enable multi-file IP optimizations (between files)
/Qwp_ipo enable multi-file IP optimizations (between files) and make
"whole program" assumption that all variables and functions seen
in the compiled sources are referenced only within those sources;
the user must guarantee that this assumption is safe
/Qipo_c generate a multi-file object file (ipo_out.obj)
/Qipo_S generate a multi-file assembly file (ipo_out.asm)

Modify the behavior of IP:
/Qip_no_inlining disable full and partial inlining (requires /Qip or /Qipo)
/Qip_no_pinlining disable partial inlining (requires /Qip or /Qipo)
/Qipo_obj force generation of real object files (requires /Qipo)

Other Advanced Performance Options:
/Qunroll[n] set maximum number of times to unroll loops. Omit n to use
default heuristics. Use n=0 to disable loop unroller.

/Qprof_dir <d> specify directory for profiling output files (*.dyn and *.dpi)
/Qprof_file <f> specify file name for profiling summary file
/Qprof_gen[x] instrument program for profiling; with the x qualifier, extra
information is gathered for use with the PROFORDER tool
/Qprof_use enable use of profiling information during optimization
/Qfnsplit[-] enable/disable function splitting (enabled with /Qprof_use)

/Qpc32 set internal FPU precision to 24 bit significand
/Qpc64 set internal FPU precision to 53 bit significand (DEFAULT)
/Qpc80 set internal FPU precision to 64 bit significand
/QIfist[-] enable/disable(DEFAULT) fast float-to-int conversions (*M)
/Qrcd same as /QIfist
/Qprec improve floating-point precision (speed impact less than /Op)
/Qprec_div improve precision of FP divides (some speed impact)
/Qfp_port round fp results at assignments & casts (some speed impact)
/Qsfalign8 may align stack for functions with 8 or 16 byte vars (DEFAULT)
/Qsfalign16 may align stack for functions with 16 byte vars
/Qsfalign force stack alignment for all functions
/Qsfalign- disable stack alignment for all functions
/Gh call __penter in function prolog; for custom user profiling

/Qvec[-] enable(DEFAULT)/disable the vectorizer
/Qvec_report[n] control amount of vectorizer diagnostic information:
n=0 no diagnostic information
n=1 indicate vectorized loops (DEFAULT)
n=2 indicate vectorized/non-vectorized loops
n=3 indicate vectorized/non-vectorized loops and prohibiting
data dependence information
n=4 indicate non-vectorized loops
n=5 indicate non-vectorized loops and prohibiting data
dependence information

/Qopenmp enable the parallelizer to generate multi-threaded
code based on the OpenMP directives
/Qopenmp_report{0|1|2} control the OpenMP parallelizer diagnostic level



 
Viewer   (2002-05-21 19:57) [15]

Output, Debug, PCH
------------------
/c compile to object (.obj) only, do not link
/S compile to assembly (.asm) only, do not link (*I)
/FA[cs] produce assembly file with optional code or source annotations
/Fa[file] name assembly file (or directory for multiple files; i.e. /FaMYDIR\)
/Fo[file] name object file (or directory for multiple files; i.e. /FoMYDIR2\)
/Fe<file> name executable file or directory
/Fm[file] name map file or directory
/Fp[file] name precompiled header file
/Yc[hfile] create precompiled header file
/Yu[hfile] use precompiled header file
/YX enable automatic precompiled header file creation/usage
/Qpchi[-] enable(DEFAULT)/disable PCH coexistence, to reduce build time
/Qpch_mem<n> preallocate <n> megabytes of memory for PCH creation
/FD generate file dependencies
/Fr[file] name source browser file (excludes local variable info)
/FR[file] name extended source browser file
/Quse_asm produce objects through the assembler
/GZ detect "release build" runtime errors in "debug build" code
/Zd produce line number information in object file
/Zi, /Z7 produce symbolic debug information in object file
/Qinline_debug_info preserve the source position of inlined code instead
of assigning the call-site source position to inlined code

Preprocessor
------------
/C don"t strip comments
/D<name>[{=|#}<text>] define macro
/QA<name>[(val)] create an assertion "name" having value "val"
/QA[-] remove all predefined macros
/E preprocess to stdout
/EP preprocess to stdout, omitting #line directives
/EP /P preprocess to file, omitting #line directives
/P preprocess to file
/FI<file> force inclusion of file
/I<dir> add directory to include file search path
/QH print include file order; don"t compile
/QM generate makefile include dependencies; don"t compile
/U<name> remove predefined macro
/u remove all predefined macros
/X remove standard directories from include file search path

Component Control
-----------------
-Qoption,<str>,<opts> pass options <opts> to tool specified by <str>
-Qlocation,<str>,<dir> set <dir> as the location of tool specified by <str>

Language
--------
/J change default char type to unsigned
/noBool disable "bool" keyword
/Qms allow compilation of certain dubious sources
/Qansi[-] enable/disable(DEFAULT) assumption of ANSI conformance
/Qrestrict enable the "restrict" keyword for disambiguating pointers
/Qvc5 enable Visual C++ 5.0 compatibility
/Qvc6 enable Visual C++ 6.0 compatibility (DEFAULT)
/Za disable Microsoft Visual C++ compiler language extensions
/Ze enable Microsoft Visual C++ compiler language extensions (DEFAULT)
/Zp[n] specify alignment constraint for structures (n=1,2,4,8,16)
/Zs check source syntax only, do not compile
/vd{0|1} disable or enable hidden vtordisp field in C++ objects
/vm<x> specify representation method for C++ pointers to members

Compiler Diagnostics
--------------------
/w disable all warnings
/W0 print only errors
/W1, /W2, /W3 print only errors and warnings (DEFAULT)
/W4 print errors, warnings, and remarks
/WX force warnings to be reported as errors
/Wport issue portability diagnostics
/Qwn<n> print a maximum of n errors
/Qwd<L1>[,<L2>,...] disable diagnostics L1 through LN
/Qwe<L1>[,<L2>,...] change severity of diagnostics L1 through LN to error
/Qww<L1>[,<L2>,...] change severity of diagnostics L1 through LN to warning
/Qwr<L1>[,<L2>,...] change severity of diagnostics L1 through LN to remark

Miscellaneous
-------------
/?, /help print this help message
/H<n> limit length of external symbols to n characters
/nologo do not display compiler version information
/Tc<file> compile file as C source
/Tp<file> compile file as C++ source
/TC compile all source or unrecognized file types as C source files
/TP compile all source or unrecognized file types as C++ source files
/V<text> embed version text in executable
/Qsox[-] enable(DEFAULT)/disable saving of compiler options and version
in the executable
/Qlong_double enable 80-bit "long double"
/Qnobss_init disable placement of zero-initialized variables in BSS (use DATA)
/QIfdiv[-] enable/disable patch for Pentium processor FDIV erratum (*M)
/QI0f[-] enable/disable patch for Pentium processor 0f erratum (*M)

Linking/Linker
--------------
/link specify that all following options are for the linker
/F<n> set the stack reserve amount specified to the linker
/LD, /LDd produce a DLL instead of an EXE ("d" = debug version)
/MD, /MDd use dynamically-loaded, multithread C runtime
/ML, /MLd use statically-loaded, single thread C runtime (/ML is DEFAULT)
/MT, /MTd use statically-loaded, multithread C runtime
/Zl omit library names from object file


 
drpass   (2002-05-22 13:25) [16]

>Agent Smith
Как ни странно, такая же программа на Delphi6 весит всегда меньше, чем на С++ Builder соответствующей версии. Причем речь даже не идет о VCL, а просто о программном коде. В случае с VCL ситуация еще хуже, так как Билдер выходит позже Delphi на полгода-год, и его библиотека пожирнее будет.
Просто в Delphi по умолчанию опция "Build with runtime packages" выключена, а в Билдере включена. Потому и разница в объеме программы :))) А не из-за крутизны компилятора Сей. Поставь и там, и там ее в одно положение, и увидишь, кто лучше оптимизирует по объему :)
А неиспользуемые функции из проги выкидывал еще ТрубоПаскаль5


 
Agent Smith   (2002-05-22 15:17) [17]

2 drpass

> Просто в Delphi по умолчанию опция "Build with runtime packages"
> выключена, а в Билдере включена. Потому и разница в объеме
> программы

Да, я это и имел в виду. Ведь большинство юзеров работают с настройками по-умолчанию. А VCL и там и там почти одинаковая.
К стати, на сколько я помню (тут я могу ошибаться) независимо от положения данной опции если размер проги выходит за 10 Мб, то он одинаков (примерно) от обоих систем.
Вот только не совсем понятна фраза

> Как ни странно, такая же программа на Delphi6 весит всегда
> меньше, чем на С++ Builder соответствующей версии

Если ты имеешь в виду навороченность VCL, то да, конечно. А ты это имеешь в виду?


 
Mystic   (2002-05-22 23:10) [18]


> К стати, главным плюсом "толстого" кода на Дельфи я считаю
> усложнение попытки взлома программы. Например, если твоя
> программа привязывается к материнке, то найти это в машинном
> коде будет довольно трудно.


Да нет, не сложно. Вот поломать программу на Vb с использованием P-кода...

Object Pascal --- язык более строгий, чем C++, потому легче поддается оптимизации. А на счет всех опций... Для критичных участков кода есть build-in assembler, а остальное оптимизировать большого смысла нет, интерес чисто теоретический.


 
VuDZ   (2002-05-22 23:38) [19]

ИМХО, на С++ проще убить прогу в смысле скорости - сделать кучу темплейтов, множественные наследования ги де не надо и пр., по-этому С и остаётся более быстрые языком. в отличие от С++

а ещё есть direct.hand.sys


 
VuDZ   (2002-05-22 23:38) [20]

ИМХО, на С++ проще убить прогу в смысле скорости - сделать кучу темплейтов, множественные наследования ги де не надо и пр., по-этому С и остаётся более быстрые языком. в отличие от С++

а ещё есть direct.hands.sys



Страницы: 1 вся ветка

Форум: "Потрепаться";
Текущий архив: 2002.06.24;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.54 MB
Время: 0.015 c
6-77545
ATLANTIDO
2002-04-13 16:23
2002.06.24
Расшареные ресурсы


3-77281
Андр
2002-05-29 14:47
2002.06.24
Обработка ошибок на русском


3-77288
Blondin
2002-05-30 18:46
2002.06.24
Проблемы с АДО, помогите


3-77276
Lena
2002-05-30 14:13
2002.06.24
Чтение из Blob-поля


1-77454
Валет
2002-06-10 13:37
2002.06.24
ListBox





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский