Android или Java потребляют больше энергии, поскольку работают на виртуальной машине?

5267
PKM

Поскольку приложения Android работают на JVM (Dalvik VM), которая в основном является виртуальным процессором, и каждая виртуальная инструкция должна быть сопоставлена ​​с собственной инструкцией базового набора микросхем, приводит ли это отображение к большему энергопотреблению из-за издержек этого отображения?

Этот вопрос можно распространить на Java, а также сформулировать так: «Используют ли приложения Java больше мощности?». Вот почему телефоны Android имеют такой ужасный срок службы батареи по сравнению с другими платформами / телефонами?

Изменить : Основываясь на ответах, я разъяснил несколько моментов, потому что я ошибочно говорил о JVM и Dalvik взаимозаменяемо. В этом бите я говорю о Java только для того, чтобы спросить, использует ли она больше энергии, и если да, относится ли это концептуально и к Android, и приводит ли это к сокращению времени автономной работы.

Контекст : цитата из Википедии:

  1. Java-байт-код аналогичен языку ассемблера для C-кода.
  2. С точки зрения компилятора виртуальная машина Java - это просто еще один процессор с набором инструкций, байт-кодом Java, для которого может быть сгенерирован код.
  3. JVM имеет стековую архитектуру. Dalvik - это виртуальная машина процесса, которая не относится к типу виртуализации, аналогичному JVM, и имеет архитектуру регистра.

Поскольку язык программирования Java компилируется в байт-код (подобный сборке) и работает на виртуальном процессоре, он обеспечивает истинную переносимость программного кода. Кроме того, поскольку JVM для Linux и Linux были портированы на открытое оборудование, комбинация может обеспечить истинную переносимость приложения по всему стеку.

Мощность : вопрос сводится, по сути, к следующему - для того же набора функций программного кода или приложения, какой процент тактовых циклов вашего процессора относится к среде выполнения. Это происходит в среде компиляции Just-In-Time современных JVM, где, если байт-код компилируется с собственной инструкцией базового набора микросхем, тогда время выполнения должно быть активным только во время Jit-компиляции. Итак, насколько больше тактов ЦП используется в среде выполнения, которая, как ожидается, приведет к увеличению энергопотребления. Меня интересует только аспект энергопотребления, а не относительная производительность по сравнению со статически типизированными и встроенными языками, и я понимаю преимущества Java. Подвопросы, которые могут быть связаны:

  • Использует ли среда выполнения Java libc для своей функциональности?
  • Какие-либо из этих точек, связанных с энергопотреблением, соответствуют Dalvik VM и Android?
  • Вместо того, чтобы обобщать плохое потребление батареи Android, не говоря об экране и беспроводных чипсетах, давайте поговорим о том, что у iPhone 5 есть батарея емкостью 1440 мАч, которая крошечна по сравнению с современными телефонами Nexus. Весь этот ход мыслей (Java, Виртуальный процессор, отображение инструкций, Android) возник, потому что друг-лоялист iphone утверждал, что это может быть вероятной причиной того, что его iphone имеет более длительное время автономной работы, чем мой (удивительный) нексус.

В любом случае, спасибо за ответы ниже.

14
Не сравнивайте батареи по их мАч. Это актуально; теоретически у вас может быть батарея емкостью 2 мАч с большей мощностью (ватт-час), чем батарея с 10000000 мАч. Зависит от напряжения. В Nexus 4 установлен аккумулятор на 8 Втч, а на iPhone 5 - 5,45 Втч. Разница в значительной степени обусловлена ​​размером экрана: у Nexus 4 диагональ дисплея составляет 4,7 ", а у iPhone 5 - 4-дюймовый, с более высоким разрешением и более высокой яркостью (608 кд / м ^ 2 против 500). также заметно отличается: Nexus 4 имеет четырехъядерный процессор с тактовой частотой 1,5 ГГц, iPhone 5 имеет двухъядерный процессор с тактовой частотой 1,3 ГГц. Horn OK Please 10 лет назад 1
По сути, iPhone работает дольше с меньшей батареей, потому что вся платформа спроектирована так, чтобы быть меньше: меньше физического пространства, меньший экран, меньший процессор, меньше ядер, меньше возможностей, меньше производительности, меньше, меньше, меньше. Телефоны на Android имеют тенденцию к противоположному направлению: больше, больше ядер, больше мощности и быстрее. Конечно, им понадобятся гораздо большие батареи, чтобы получить такое же время автономной работы. Иногда даже большая батарея не может должным образом компенсировать потребление, и в этом случае у вас телефон с плохим временем автономной работы. Horn OK Please 10 лет назад 1

5 ответов на вопрос

25
Horn OK Please

Your question is based on many flawed assumptions. Let me attempt to clear them up:

  • You said "JVM (Dalvik VM)". That's like saying "Airplane (Bicycle)". These two things have absolutely nothing to do with one another.

  • You said "...which is basically a virtual processor". Simply false. It is not the case that, every time the words "Virtual Machine" or acronym "VM" is used in a technical context, that it is essentially equivalent to VMware Workstation. This is because products like VMware do in fact emulate an entire computer, not only the CPU, and are running an operating system on top of another operating system. Dalvik VM does not work like that. Not even close.

  • Java is just a programming language. It's syntax. Android/Dalvik programs happen to use the same or very similar syntax to a completely unrelated desktop/server programming language called Java, which runs on a Java Virtual Machine. In theory, you could write Java code that is very nearly the same speed as C code, since they are both high level programming languages. The devil's in the details of the implementation of the library calls and the way that the runtime is designed, which has very little to do with the syntax of the language.

  • It is an over-generalization to say that Dalvik VM, the Sun Java Hotspot JVM, or the Java programming language syntax is responsible for high power consumption. The reason is that you have to compare whatever you're talking about to the performance of something else. In the most general case, when you're just comparing the "best-case" capabilities of both platforms, it is in principle possible to make Dalvik apps that are just as fast, or faster, than programs on any other platform. Other than automatic memory management and JIT compilation -- features which are standard in almost all programming environments these days, including on iOS and in JavaScript / HTML5 -- there is very little that separates Dalvik from Objective-C, .NET, Ruby, the Oracle Hotspot JVM, Python, and so on.

  • The perception that "Java is slow" is due to a problem with old versions of Java, in that they either did not have a Just-In-Time Compiler (JIT), or the JIT they had was very limited in functionality. The JVM has had a Just-In Time Compiler for a very long time now. A JIT compiler is a part of the runtime (for instance, the JVM) that takes processor-independent bytecode -- for example Java bytecode -- and compiles it into native instructions for the CPU. This process is done when the Java program launches, and advanced JIT compilers can optimize individual functions or instructions at runtime to improve their performance based on observed results. For instance, if a method returns true every single time it's called, but it isn't obvious from the original bytecode that it would do so, the JIT compiler can recognize that it just returns true, and replace the function call with a hard-coded value of "true". This is just one example.

  • JIT compilation and runtime dynamic code analysis techniques have been making huge advances in recent years. Many in the computer science community believe that, in another decade or two, the sophisticated analysis available in dynamically interpreted/compiled languages, such as Java, C# and Ruby, will be so advanced that, in most cases, these languages will execute faster at runtime than statically-compiled languages like C and C++. That's because static compilers are usually limited to compiling code at build-time, and the code is not modified at runtime. But in a runtime environment where the code of the program can re-write itself during execution to perform more efficiently, there is an enormous amount of upside that can be achieved by analyzing the performance of the code and making adjustments to reduce the complexity of the code or the number of instructions that are run on the CPU. For frequently-called code, the time investment required to perform the analysis is far outweighed by the performance benefits of repeatedly calling faster code.

  • It should be noted that the Android Dalvik VM also contains a JIT, and that it does not use the same bytecode format as the Sun/Oracle JVM. Dalvik's JIT is optimized for low memory environments, and it is very advanced as far as runtime performance enhancements. So it is somewhat of a coincidence that the JVM and Dalvik implement similar optimizations for their respective Java-based runtime environment, but under the hood they are quite different.

  • Don't forget that Dalvik itself; the Linux kernel; low-level system processes; and the core of Android web browsers (both Firefox and Chrome) are written in native C/C++, and so they do not have any of the overhead concerns that a Dalvik program would. This is the same as iOS. If you're talking about pure Android and not the carrier/third-party bloat that sits on top of it, a very large proportion of what comprises core Android is not written using Dalvik.

  • Application developers on Android can also, at their option, write native code, bypassing Dalvik. If an application developer felt that Dalvik was acting as a bottleneck in the performance of their code, or causing it to drain too much battery, they could simply write C/C++ or even assembly code if they chose to, without having to obtain Google's approval to do so, and distribute their app like that.

Here are some actual reasons why an Android battery-powered device, or any device, may have problems with battery life:

  • Applications that keep the CPU, screen, or data connection awake. In particular, 4G chipsets such as LTE use a great deal of energy when they are powered on, so if you have background programs that continually wake up the LTE chip to transfer a few kilobytes of data, that will drain your battery very fast. The screen on modern smartphones and tablets is also very energy-intensive, unless you turn the brightness down to minimal.

  • "Bloatware" that is required to be on the device, and can't be uninstalled. Some unscrupulous carriers require you to run bloatware that takes up CPU cycles and keeps the data connection awake. This can be either due to incompetence on the part of the software developers of the bloatware, or an intentional goal of monitoring your activities on your smartphone and sending them to a remote server for data mining, which is very energy-intensive for your battery.

Finally, I disagree with your assessment that Android has worse battery life problems than on other mobile platforms. Certain phones and devices may indeed have battery life problems, either due to the capacity of the battery relative to the energy consumption of the hardware; poorly optimized power settings (elected by the user, the carrier, or the manufacturer); or bloatware apps that keep chips in the phone awake all the time. But for every example of a device that has battery problems, I can give you a counterexample of a device with excellent battery life. There's no simple way to generalize that "it's Dalvik" or "it's Linux" or "it's Java". Power optimization is a complicated hardware/software mish-mosh of competing concerns, including performance, responsiveness, and the user expectations for battery life, with pros and cons to each choice. To fully understand the power profile of a device, you have to take a close look at the battery itself, all of the hardware, and all of the software running on the device.

+1 Это немного похоже, но у него есть все, даже хороший технический ответ. Doktoro Reichard 10 лет назад 1
Спасибо, все честно. Я неправильно использовал некоторые термины как взаимозаменяемые, потому что спрашивал что-то, чего не знал. Сделайте некоторые изменения в самом вопросе сейчас, если вы все еще заинтересованы. PKM 10 лет назад 0
Этот ответ довольно информативен, но далек от вопроса. Суть вопроса заключалась в том, использует ли служебная нагрузка виртуальной машины больше процессорного времени, чем экономит за счет оптимизации, которую она использует. Это в большей степени объясняет, почему Android лучше, чем iOs, хотя у этого вопроса был и намек на это с другой стороны. PSIXO 9 лет назад 0
Здесь тоже есть ошибочное предположение. IOS не хватает автоматического управления памятью Mac OS. И это действительно то управление, которое делает Dalvik "Java" со всеми его типичными проблемами. Несколько месяцев назад был довольно хороший обзор проблем сбора мусора (GC), с которыми сталкивается Дальвик: http://www.anandtech.com/show/8231/a-closer-look-at-android-runtime-art- in-android-l / 2 - если они тоже влияют на время автономной работы или просто производительность, я не могу сказать. pvblivs 9 лет назад 0
@pvblivs Хотя это правда, что при написании «высокоуровневого» кода приложения для iOS вместо GC используется автоматический подсчет ссылок, в то время как Dalvik использует GC и «поэтому» (я не говорю, что это обязательно так, просто кажется, что вы спорите что, и это, по крайней мере, правдоподобно) iOS «более эффективна», чем Android… Вы все еще упускаете из виду, что приложения Android не * должны * быть написаны на Java, и фактически могут быть написаны на ассемблер или даже собственный код ARM, если хотите! Чрезвычайно чувствительные к производительности приложения и встроенные компоненты * должны * использовать нативный код без GC. Horn OK Please 9 лет назад 0
Например, библиотека C Android, [Bionic] (http://en.wikipedia.org/wiki/Bionic_%28software%29), не использует сборку мусора для управления памятью, которую она выделяет для выполнения своей работы. , Ничто не мешает любому другому приложению или программе на Android делать то же самое, потому что программы, написанные третьими лицами, и программы, написанные Google, получают те же инструменты разработки на Android. Да, есть разница в * разрешениях * и доступе к устройствам на нерутированных телефонах, но это проблема безопасности / контроля оператора, а не проблема программирования / техническая проблема. Horn OK Please 9 лет назад 0
Проблема, которая, по-видимому, возникает, заключается в том, что многие из существующих приложений * на самом деле * выбирают выполнение чрезвычайно чувствительных к производительности операций (большие циклы, связанные с обработкой мультимедиа и т. Д.) Поверх Dalvik или другой среды JIT / GC (JavaScript является еще одним большим один). Это серьезная критика, но не основной платформы, а только тех конкретных приложений и сервисов. Horn OK Please 9 лет назад 0
Последний комментарий, обещаю: для того, чтобы GC оказал минимальное влияние на производительность Android, вы должны * записать все ваши интенсивные циклы, подпрограммы ввода-вывода мультимедиа и т. Д. В нативный код, используя стек -распределенные, управляемые вручную данные или автоматически подсчитанные ссылки; и затем, когда вы пишете высокоуровневый клейкий код (обработчики событий, расположение пользовательского интерфейса вашего приложения и т. д.), объем и сложность кода достаточно малы, чтобы GC мог его обработать. Этот подход достаточно хорошо работает на рабочем столе GNU / Linux с такими вещами, как Ruby / Python / JavaScript. Horn OK Please 9 лет назад 0
@allquixotic: Хорошо, я понимаю дух вашего ответа. Я немного разрываюсь по этому поводу, потому что реальность, безусловно, сильно отличается от теории. Вы, конечно, могли бы доказать, что IOS предлагает привязки JS. Но никто не ответил бы: IOS медленнее, потому что они предлагают JS. Таким образом, ответ здесь выглядит следующим образом: да, Java создает проблемы, как и виртуальная машина. Нет, Android конечно нет. Я умный, вы можете добиться большего успеха на этой платформе. pvblivs 9 лет назад 0
5
Mark Lopez

In this answer I will be comparing performance with Android and IOS as the two take up over 80% of the market share.

Java apps do not use more power. (http://www.javarants.com/2004/05/04/looks-like-apple-should-switch/) Oracle's Java VM or in reality Google's Dalvik VM is considered much more effient than IOS's Objective-C. Java is able to optimise code before it's executed on the phone which could result in much better performance. Java libraries are Open Source and therefore have been optimised by hundreds of different developers. On the other hand with IOS only Apple developers are able to change the code. Less review = less potential performance.

Android programs are also able to run native C code which could be disputed as faster than again Object-C (the only language supported on IOS).

The reason why Google decided on using the Dalvik VM is for portability. I know of four different CPU architectures that Android can official run on (ARM, MIPS, x86, I.MX). While every other phone OS can only use one (ARM). (http://en.wikipedia.org/wiki/Comparison_of_mobile_operating_systems) So comparing different CPU types with for example IPhone is unfair. If Android was ran on IPhone, Android would have comparable to superior performance and battery life.

"do Java applications use more power ?" Simply no.
Why Android phones have such appalling battery lives as compared to other platforms/phones ? Many Android phones are built cheaper than Apple's IPhone, but look at the price difference. The IPhone cost more because of the much larger battery with in it (and it's on average slower CPU). My android phone (Google Galaxy Nexus) has comparable battery life to the IPhone 4G but has much faster hardware specs (1GHz vs. 1.2GHZ).

EDIT: Java can optimise code without the programmer's knowledge required. Perfect, C code will always run faster than Java / Objective-C / C#; That said, how many programmers out there are perfect? At the JVM level Java and libraries will always be "more perfect" because of its open source development principles. (http://www.infoq.com/news/2012/03/Defects-Open-Source-Commercial)

EDIT 2: Small tidbit of information: Lenovo's new P780 Android Phone - 42 hours talk vs 12 hours on IPhone.

Я бы сказал, что сам * вопрос * делает совершенно необоснованные заявления типа «... телефоны Android имеют такое ужасное время автономной работы по сравнению с другими платформами / телефонами». Просто не правда. Horn OK Please 10 лет назад 1
Хотелось бы добавить, что ваша первая ссылка - ИМХО сомнительного качества: файлы эталонных тестов пропали, а комментатор опроверг мнение автора ссылки. Этот пост кажется предвзятым из-за отсутствия неопровержимых источников и субъективных утверждений. Doktoro Reichard 10 лет назад 0
Ну, первый комментатор вроде как. Без подробного тестирования все ответы будут предвзятыми. Я согласен с тем, что время автономной работы телефонов Android довольно ужасное, но это, конечно, не из-за ВМ, как упоминали многие. PSIXO 9 лет назад 0
Вскоре вся эта информация будет устаревшей с приходом среды выполнения ART в Android. Mark Lopez 9 лет назад 0
3
davidgo

Yes, it does relate to increased power consumption - layers of abstraction will do that. It also leads to a decrease in speed (opposite side of the same coin - if something has greater overhead it will take longer to perform and thus use more CPU). If I understand correctly that is one of the advantages of what the NDK does - allow speedups for specific processors by writing specific code.

That said, for most jobs I'd imagine the "power related" overheads of running a VM are dwarfed by other considerations - for most programs the use of screen and radios will consume most of the power.

Вы правы. A Даже если использовать черные элементы интерфейса на экране Oled, это будет намного экономичнее, чем использование NDK против SDK в большинстве случаев. PSIXO 9 лет назад 0
3
Doktoro Reichard

With regards to all other posters I believe what matters here most is not whether C/C++/Java exists but what the applications are doing.

Since power consumption maps directly with processing, I would ask myself what processing would a program do.

Say you're adding numbers. Say you're adding 2 with 2 on an infinite loop until you reach 2.000.000. Two questions arise:

  1. How is it implemented: Is it a for-loop? Is it a while loop? (Is it a Goto/Label hack?)
  2. How is the code being optimized.

These two questions ultimately define how many operations the processor needs to do and ultimately, how much power a device uses. This being said, the "overhead" of running a virtualized environment might be negligible due to the previous optimizing made by Java on the whole of the program, but then again, it all depends on what the application is doing.

0

Yes.

Virtual machines 'do everything twice', and not necessarily efficiently. So, they will use at least twice as much power to process the same instructions as a 'real machine'. The presence of a virtual machine slows things down and uses more power. Basically, OSes like iOS and WIndows will do everything faster and with less power consumption.

This translates to real differences in screen transitions, page loading, navigation, things like that. Currently Im comparing Android (VM) and Windows Phone, and even with a slower processor (1GHz vs 1.6GHz), Windows significantly outperforms Android doing the same kind of tasks.

However, what attracts the attention of most people is when they install an app and suddenly their battery gets used up more quickly. Thats not really due to the virtual machine, but an app that uses resources hungrily.

The whole reason for a virtual machine OS, portability, isnt a good reason to base an OS on. Do you see people buying phones with their favorite architecture and using Android because its portable? Do you see people giving up higher performance and reliability and putting android on their non-android phones? People buy an Android Phone, or a Windows Phone, or an IPhone, etc. To sacrifice performance for portability in low cost devices is impractical. It was a good idea that became a fail.

Похожие вопросы