简体   繁体   English

如何获取Ant中的availableProcessors数量

[英]How can I get the number of availableProcessors in Ant

我想从我的Ant构建脚本获取availableProcessors的数量(即从Runtime.getRuntime()。availableProcessors()返回的值。是否存在包含此值的现有属性,或者我是否必须编写自定义ant任务?

This post by Ilia Chemodanov explains two solutions nicely. Ilia Chemodanov的这篇文章很好地解释了两个解决方案。

If you don't want to compile and import a Java class you can do it in pure ant: (though it is pretty hacky) 如果您不想编译和导入Java类,可以在纯蚂蚁中执行:(虽然它非常hacky)

<target name="get-cores">
    <property environment="env"/>
    <!-- support for Windows -->
    <condition property="cores.count" value="${env.NUMBER_OF_PROCESSORS}">
        <os family="windows" />
    </condition>
    <!-- support for Linux and Solaris (package SUNWgnu-coreutils is required) -->
    <exec executable="nproc" outputproperty="cores.count" os="Linux,SunOS,Solaris">
        <arg value="--all"/>
    </exec>
    <!-- support for Mac OS X -->
    <exec executable="sysctl" outputproperty="cores.count" os="Mac OS X">
        <arg value="-n"/>
        <arg value="hw.ncpu"/>
    </exec>
    <echo message="Number of cores: ${cores.count}"/>
</target>

编写自定义ant任务 ,就像写一个类一样简单

The JVM does not provide such a property and neither does ant. JVM不提供这样的属性,也不提供ant。 Instead of writing a custom task you could do one of the following: 您可以执行以下操作之一,而不是编写自定义任务:

  1. Write a Java class that prints the number of processors to standard output. 编写一个Java类,将处理器的数量打印到标准输出。 Use the java task with the outputproperty attribute to set the value to a property for use in ant. 使用带有outputproperty属性的java任务将值设置为要在ant中使用的属性。
  2. If you are only ever building one a single platform use the exec task to call something native that prints the number of processors to standard output. 如果您只构建一个平台,请使用exec任务调用本机,将处理器数量打印到标准输出。 As above use the outputproperty attribute to set the value to a property for use in ant. 如上所述,使用outputproperty属性将值设置为在ant中使用的属性。

Like @dfa mentioned, writing your own custom task it's a good option. 就像@dfa提到的那样,编写自己的自定义任务是一个不错的选择。

However, if the host that builds your service is different from the host running it, then the number of cores will differ (you will get the number of available processors of the host that build your service). 但是,如果构建服务的主机与运行它的主机不同,则核心数将不同(您将获得构建服务的主机的可用处理器数)。

If you DON'T want that, then you can just use a small shell script inside your build script, something like this (for UNIX like OSs): 如果你不想那样,那么你可以在你的构建脚本中使用一个小的shell脚本,就像这样(对于像OS这样的UNIX):

$(/usr/bin/nproc --all)

I'd check if the command exists first, if(type /usr/bin/nproc) .... but that depends on how you want to implement it. 我先检查命令是否存在, if(type /usr/bin/nproc) ....但这取决于你想如何实现它。

I never heard about such a property, thus I think you should write your custom task. 我从来没有听说过这样的属性,因此我认为你应该编写自定义任务。

Manu 马努

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM