Linux CPU utilization: Difference between revisions
no edit summary
(VBA will not run on Linux) |
No edit summary |
||
(31 intermediate revisions by 16 users not shown) | |||
Line 26:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
BEGIN {
prev_total = 0
Line 42:
}
}
</syntaxhighlight>
Invocation and output:
<pre>
Line 53:
</pre>
Alternatively, the output can continuously overwrite itself to remain on a single line a la the [[#UNIX Shell|UNIX Shell]] version, by replacing the <code>print</code> line with:
<syntaxhighlight lang="awk">
printf "\rCPU: %5.1f%% \b\b",(1-(idle-prev_idle)/(total-prev_total))*100
</syntaxhighlight>
=={{header|C}}==
On Linux, sleep accepts seconds, on Windows, milliseconds. So if you are planning to test this on Windows and then port it to Linux .....The implementation below has been tested on a Linux machine.
<syntaxhighlight lang="c">
#include<stdlib.h>
#include<string.h>
Line 83:
while(times>0){
FILE* fp = fopen("/proc/stat","r");
i = 0;
fgets(str,100,fp);
fclose(fp);
token = strtok(str,d);
sum = 0;
while(token!=NULL){
token = strtok(NULL,d);
Line 97:
i++;
}
}
idleFraction = 100 - (idle-lastIdle)*100.0/(sum-lastSum);
printf("
lastIdle = idle;
lastSum = sum;
times--;
sleep(lag);
}
}
return 0;
}
</syntaxhighlight>
Invocation and output :
<pre>
/home/aamrun/rosettaCode>./cpuStat 3 1
</pre>
=={{header|C++}}==
<
#include <iostream>
#include <numeric>
Line 155:
previous_total_time = total_time;
}
}</
{{out}}
<pre>
Line 165:
</pre>
===
==== Qt Console Variant 1 ====
{{uses from|library|Qt|component1=QFile}}
A very basic [[Qt]]-port of the the [[#C++|C++]] implementation above.
<
#include <QFile>
#include <unistd.h>
Line 188:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 201:
{{uses from|library|Qt|component1=QCoreApplication|component2=QObject|component3=QFile}}
An event-based [[Qt]] console implementation. Note, this version does not rely on any system-dependant headers or functions.
<
#include <QCoreApplication>
#include <QFile>
Line 236:
return app.exec();
}
</syntaxhighlight>
{{out}}
<pre>
Line 250:
{{uses from|library|Qt|component1=QApplication|component2=QProgressDialog|component3=QFile}}
A GUI version, using the [[Qt]] framework.
<
#include <QApplication>
#include <QFile>
Line 292:
return app.exec();
}
</syntaxhighlight>
{{out}}
[[File:Linux CPU utilization Qt GUI.png]]
=={{header|C#}}==
<syntaxhighlight lang="csharp">
var prevIdle = 0f;
var prevTotal = 0f;
while (true)
{
var cpuLine = File
.ReadAllLines("/proc/stat")
.First()
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.Select(float.Parse)
.ToArray();
var idle = cpuLine[3];
var total = cpuLine.Sum();
var percent = 100.0 * (1.0 - (idle - prevIdle) / (total - prevTotal));
Console.WriteLine($"{percent:0.00}%");
prevIdle = idle;
prevTotal = total;
Thread.Sleep(1000);
}
</syntaxhighlight>
Output:
<pre>
20.88%
15.38%
8.33%
8.33%
0.00%
8.33%
</pre>
=={{header|Dart}}==
<syntaxhighlight lang="javascript">
#!/usr/bin/env dart
import 'dart:io';
List<int> load() {
File f = File('/proc/stat');
List<String> lines = f.readAsLinesSync();
List<int> loads = lines[0]
.substring("cpu ".length)
.split(" ")
.map((String token) => int.parse(token))
.toList();
int idle = loads[3];
int total = loads.reduce((int a, int b) => a + b);
return [idle, total];
}
void main() {
List<int> idleTotalPrev = [0, 0];
while (true) {
List<int> idleTotal = load();
int dTotal = idleTotal[0] - idleTotalPrev[0];
int dLoad = idleTotal[1] - idleTotalPrev[1];
idleTotalPrev = idleTotal;
double percent = 100.0 * (1.0 - dTotal / dLoad);
print("${percent.toStringAsFixed(2)}%");
sleep(const Duration(seconds: 1));
}
}
</syntaxhighlight>
Output:
<pre>
13.27%
1.25%
0.75%
1.37%
0.63%
0.63%
</pre>
=={{header|Fortran}}==
<
Program CPUusage
implicit none
Line 330 ⟶ 416:
end do
end program CPUusage
</syntaxhighlight>
{{out}}
Line 344 ⟶ 430:
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 388 ⟶ 474:
time.Sleep(time.Second)
}
}</
{{out}}
Line 407 ⟶ 493:
=={{header|Haskell}}==
<
splitString :: Char -> String -> [String]
Line 425 ⟶ 511:
theTimes <- fmap lines $ readFile "/proc/stat"
putStr $ show $ computeUsage $ head theTimes
putStrLn " %"</
{{out}}
Line 432 ⟶ 518:
=={{header|Icon}} and {{header|Unicon}}==
<
# utilization.icn, percentage of running cpu time used versus idle time
#
Line 469 ⟶ 555:
}
return stats
end</
{{out}}
Line 481 ⟶ 567:
Overall utilization: 4.994135168922565%
Interval utilization: 4.878048780487809%</pre>
=={{header|J}}==
<
if. 0>nc<'PREVCPUTPCT' do. PREVCPUTPCT=:0 end.
old=. PREVCPUTPCT
PREVCPUTPCT=:
100*1-(
)</
Example use:
<
1.76237</
Notes: this gives the average non-idle time since the last time this verb was used. If for some reason /proc/stat were not updated between calls, the result would be 100 (percent), which seems appropriate.
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
</syntaxhighlight>
<syntaxhighlight lang="java">
public static void main(String[] args) throws IOException {
double[] percentages = parseUtilization(procStat());
System.out.printf("%-10s %5.2f%%%n", "idle", percentages[0] * 100);
System.out.printf("%-10s %5.2f%%", "not-idle", percentages[1] * 100);
}
static String procStat() throws IOException {
File file = new File("/proc/stat");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
return reader.readLine();
}
}
/** @return idle and not-idle percentage values */
static double[] parseUtilization(String string) {
string = string.substring(4).stripLeading();
int total = 0;
double idle = 0;
double notIdle;
int index = 0;
for (String value : string.split(" ")) {
if (index == 3)
idle = Integer.parseInt(value);
total += Integer.parseInt(value);
index++;
}
idle /= total;
notIdle = 1 - idle;
return new double[] { idle, notIdle };
}
</syntaxhighlight>
<pre>
idle 93.33%
not-idle 6.67%
</pre>
<br />
An alternate demonstration
<syntaxhighlight lang="java">import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.NumberFormat;
import java.time.Duration;
import java.util.Timer;
import java.util.TimerTask;
/* Idiomatic Java
*This certainly could've been done much shorter, but I'm glad with the way it came out
* */
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// this demonstrates the use of Duration class
final var period = Duration.ofSeconds(1);
new Timer().schedule(new CpuUtilizationTask(), 0, period.toMillis());
}
/* By extending the TimerTask abstract class, we're able to use the
* Timer scheduling class */
static class CpuUtilizationTask extends TimerTask {
private final String STAT_FILE_HEADER = "cpu ";
private final NumberFormat percentFormatter;
private final RandomAccessFile statPointer;
long previousIdleTime = 0, previousTotalTime = 0;
public CpuUtilizationTask() throws FileNotFoundException {
this.percentFormatter = NumberFormat.getPercentInstance();
percentFormatter.setMaximumFractionDigits(2);
var statFile = new File("/proc/stat");
/* by using the RandomAcessFile, we're able to keep an open file stream for
* as long as this object lives, making further file openings unnecessary */
this.statPointer = new RandomAccessFile(statFile, "r");
}
@Override
public void run() {
try {
var values = statPointer.readLine()
.substring(STAT_FILE_HEADER.length())
.split(" ");
/* because Java doesn't have unsigned primitive types, we have to use the boxed
* Long's parseUsigned method. It does what it says it does.
* The rest of the arithmetic can go on as normal.
* I've seen solutions reading the value as integers. They're NOT!*/
var idleTime = Long.parseUnsignedLong(values[3]);
var totalTime = 0L;
for (String value : values) {
totalTime += Long.parseUnsignedLong(value);
}
var idleTimeDelta = idleTime - previousIdleTime;
var totalTimeDelta = totalTime - previousTotalTime;
var utilization = 1 - ((double) idleTimeDelta) / totalTimeDelta;
/* Again, this is showing one more advantage of doing idiomatic Java
* we're doing locale aware percentage formatting */
System.out.println(percentFormatter.format(utilization));
previousIdleTime = idleTime;
previousTotalTime = totalTime;
// take us back to the beginning of the file, so we don't have to reopen it
statPointer.seek(0);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}</syntaxhighlight>
=={{header|Julia}}==
Line 503 ⟶ 710:
{{trans|Python}}
<
lastidle = lasttotal = 0
while true
Line 517 ⟶ 724:
end
main()</
=={{header|Kotlin}}==
<
import java.io.FileReader
Line 546 ⟶ 753:
Thread.sleep(1000)
}
}</
Sample output:
Line 561 ⟶ 768:
8 : 4.040
9 : 2.525
</pre>
=={{header|Nim}}==
<syntaxhighlight lang="nim">import math, sequtils, strutils
let firstLine = "/proc/stat".readLines(1)[0]
let values = firstLine.splitWhitespace()[1..^1].map(parseInt)
let totalTime = sum(values)
let idleFrac = values[3] / totalTime
let notIdlePerc = (1 - idleFrac) * 100
echo "CPU utilization = ", notIdlePerc.formatFloat(ffDecimal, precision = 1), " %"</syntaxhighlight>
{{out}}
<pre>CPU utilization = 7.9 %</pre>
=={{header|Pascal}}==
==={{header|Free Pascal}}===
<syntaxhighlight lang="pascal">
Program CPU_Utilization;
{$mode ObjFPC}
{$H+}
uses
sysutils, strutils;
const
C_INFNAME = '/proc/stat';
var
filestr: ansistring;
tfIn: TextFile;
a: TStringArray;
i, total, idle: uint32;
PrevTotal: uint32 = 0;
PrevIdle: uint32 = 0;
begin
AssignFile(tfIn, C_INFNAME);
try
while True do
begin
Reset(tfIn);
ReadLn(tfIn, filestr); // ReadLn reads a line from the file
a := filestr.Split([' ']);
total := 0;
for i := 2 to High(a) do
Inc(total, StrToInt(a[i]));
idle := StrToInt(a[5]); // there is an empty field
Writeln((1.0 - (idle - PrevIdle) / (total - PrevTotal)) * 100:4:1, '%');
PrevIdle := idle;
PrevTotal := total;
Sleep(500);
end;
finally
CloseFile(tfIn); // Close the file when done
end;
end.
</syntaxhighlight>
{{out}}
<pre>
2.8%
2.0%
0.8%
1.0%
</pre>
=={{header|Perl}}==
<
$last_idle = 0;
Line 579 ⟶ 852:
printf "Utilization: %0.1f%%\n", 100 * (1 - $delta_idle / $delta_total);
sleep 1;
}</
{{out}}
<pre>Utilization: 38.6%
Line 587 ⟶ 860:
</pre>
=={{header|
{{trans|Python}}
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--without js -- (file i/o)</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> <span style="color: #000080;font-style:italic;">-- (using the following constant)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"cpu 259246 7001 60190 34250993 137517 772 0"</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">last_idle</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">last_total</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000080;font-style:italic;">--while true do
-- integer fn = open("/proc/stat","r")
-- sequence line = trim(gets(fn))
-- close(fn)</span>
<span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">{{</span><span style="color: #000000;">line</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]}}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">idle</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">line</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">total</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">idle_delta</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">idle</span> <span style="color: #0000FF;">-</span> <span style="color: #000000;">last_idle</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">total_delta</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">total</span> <span style="color: #0000FF;">-</span> <span style="color: #000000;">last_total</span>
<span style="color: #000000;">last_idle</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">idle</span>
<span style="color: #000000;">last_total</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">total</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">utilisation</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">idle_delta</span><span style="color: #0000FF;">/</span><span style="color: #000000;">total_delta</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%5.1f%%\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">utilisation</span><span style="color: #0000FF;">})</span>
<span style="color: #000080;font-style:italic;">-- printf(1,"%5.1f%%\r",{utilisation})
-- sleep(1)
-- if get_key()=#1B then exit end if
--end while</span>
<!--</syntaxhighlight>-->
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(scl 8)
(let (Idl 0 Ttl 0)
(loop
(in "/proc/stat"
(setq L (make (do 10 (link (read))))) )
(setq I (get L 4) S (sum prog L))
(prinl
(round
(*/
100.0
(-
1.0
(*/
1.0
(- I (swap 'Idl I))
(- S (swap 'Ttl S)) ) )
1.0 )
1 )
'% )
(wait 1000) ) ) )</syntaxhighlight>
=={{header|Python}}==
<
from time import sleep
Line 614 ⟶ 927:
utilisation = 100.0 * (1.0 - idle_delta / total_delta)
print('%5.1f%%' % utilisation, end='\r')
sleep(5)</
{{out}}
Line 634 ⟶ 947:
=={{header|Racket}}==
<
(require racket/string)
Line 660 ⟶ 973:
(sleep 1)
(loop))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>my $last-total = 0;
my $last-idle = 0;
loop {
my $Δ-total = (my $this-total = [+] my @cpu = "/proc/stat".IO.lines[0].words[1..*]) - $last-total;
my $Δ-idle = (my $this-idle = @cpu[3]) - $last-idle;
$last-total = $this-total;
$last-idle = $this-idle;
print "\b" x 40, (100 * (1 - $Δ-idle / $Δ-total)).fmt("Utilization: %0.1f%% ");
sleep(1);
}</syntaxhighlight>
=={{header|REXX}}==
This REXX version tests to see if the <big> /proc/stat </big> file was updated.
It also supports the (user) option to HALT the process (by pressing Ctrl-Break).
<syntaxhighlight lang="rexx">/*REXX pgm displays current CPU utilization (as a percentage) as per file: /proc/stat */
signal on halt /*enable handling of Ctrl─Break (halt).*/
numeric digits 20 /*ensure enough decimal digits for pgm.*/
parse arg n wait iFID . /*obtain optional arguments from the CL*/
if n=='' | n="," then n= 10 /*Not specified? Then use the default.*/
if wait=='' | wait="," then wait= 1 /* " " " " " " */
if iFID=='' | iFID="," then iFID= '/proc/stat' /* " " " " " " */
prevTot = 0; prevIdle= 0 /*initialize the prevTot and prevIdle. */
do j=1 for n /*process CPU utilization N times. */
parse value linein(iFID, 1) with . $ /*read the 1st line and ignore 1st word*/
tot= 0 /*initalize TOT (total time) to zero.*/
do k=1 for min(8, words($) ) /*only process up to eight numbers in $*/
@.k= word($,k) /*assign the times to an array (@). */
tot= tot + @.k /*add all the times from the 1st line. */
end /*k*/ /*@.4 is the idle time for this cycle.*/
div= tot - prevTot /*DIV may be zero if file isn't updated*/
if div\=0 then say format(((1-(@.4-prevIdle)/div))*100,3,5)"%" /*display CPU busy.*/
prevTot= tot; prevIdle= @.4 /*set the previous TOT and prevIdle.*/
call sleep wait /*cause this pgm to sleep WAIT secs.*/
end /*j*/
/*stick a fork in it, we're all done. */
halt: /*come here when Ctrl-Break pressed.*/</syntaxhighlight><br><br>
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">val delay = Time.fromSeconds 2
fun p100 (part, full) = (200 * part div full + 1) div 2
val read1stLine =
(fn strm => TextIO.inputLine strm before TextIO.closeIn strm) o TextIO.openIn
val getColumns = Option.map (String.tokens Char.isSpace) o read1stLine
fun cpuStat list = (List.nth (list, 3), foldl op+ 0 list)
fun printStat (list, (idle, total)) =
let
val newStat as (idle', total') = cpuStat (map (valOf o Int.fromString) list)
in
print (Int.toString (100 - p100 (idle' - idle, total' - total)) ^ "%\n");
OS.Process.sleep delay;
newStat
end
fun mainLoop prev =
case getColumns "/proc/stat" of
SOME ("cpu" :: list) => mainLoop (printStat (list, prev))
| _ => ()
val () = mainLoop (0, 0)</syntaxhighlight>
=={{header|Tcl}}==
Line 673 ⟶ 1,057:
A more reusable implementation might take a command as an argument to stat, and allow that command to interrupt the loop with <tt>return false</tt> or even <tt>break</tt>.
<
proc stat {} {
Line 714 ⟶ 1,098:
}
coroutine watchstat stat</
{{Out}}
Line 724 ⟶ 1,108:
{{works with|bash}}
Example taken, verbatim, from [https://github.com/pcolby/scripts/blob/master/cpu.sh Github].
<
# by Paul Colby (http://colby.id.au), no rights reserved ;)
Line 732 ⟶ 1,116:
while true; do
# Get the total CPU statistics, discarding the 'cpu ' prefix.
CPU=(
IDLE=${CPU[3]} # Just the idle CPU time.
# Calculate the total CPU time.
TOTAL=0
for VALUE in "${CPU[@]:0:8}"; do
done
# Calculate the CPU usage since we last checked.
echo -en "\rCPU: $DIFF_USAGE% \b\b"
Line 753 ⟶ 1,137:
# Wait before checking again.
sleep 1
done</
{{out}}Each successive output overwrites the previous output, so there is only ever one line, but that line keeps updating in-place.
<pre>CPU: 1%</pre>
=={{header|Ursa}}==
<
# linux cpu utilization
#
Line 816 ⟶ 1,200:
end for
out "\r" console
end while</
=={{header|Wren}}==
{{libheader|Wren-fmt}}
For some reason (probably because it's a ''virtual'' file) Wren-cli is unable to read /proc/stat properly. We therefore need to fall back on an embedded program with the C host getting the first line of the file for us so we can analyze it.
The figure at time 0 is the cumulative CPU usage since boot time.
<syntaxhighlight lang="wren">/* Linux_CPU_utilization.wren */
import "./fmt" for Fmt
class C {
// get the first line from /proc/stat
foreign static procStat1
foreign static sleep(secs)
}
var prevIdleTime = 0
var prevTotalTime = 0
System.print("CPU usage \% at 1 second intervals:\n")
for (i in 0..9) {
var line = C.procStat1[3..-1].trim()
var times = line.split(" ")[0..7].map { |t| Num.fromString(t) }.toList
var totalTime = times.reduce { |acc, t| acc + t }
var idleTime = times[3]
var deltaIdleTime = idleTime - prevIdleTime
var deltaTotalTime = totalTime - prevTotalTime
var cpuUsage = (1 - deltaIdleTime/deltaTotalTime) * 100
Fmt.print("$d : $6.3f", i, cpuUsage)
prevIdleTime = idleTime
prevTotalTime = totalTime
C.sleep(1)
}</syntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<syntaxhighlight lang="c">/* gcc Linux_CPU_utilization.c -o Linux_CPU_utilization -lwren -lm */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
/* C <=> Wren interface functions */
void C_procStat1(WrenVM* vm) {
FILE* fp = fopen("/proc/stat","r");
char str[100];
fgets(str, 100, fp);
fclose(fp);
wrenSetSlotString(vm, 0, str);
}
void C_sleep(WrenVM* vm) {
int seconds = (int)wrenGetSlotDouble(vm, 1);
sleep(seconds);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "procStat1") == 0) return C_procStat1;
if (isStatic && strcmp(signature, "sleep(_)") == 0) return C_sleep;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Linux_CPU_utilization.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
{{out}}
Sample output:
<pre>
CPU usage % at 1 second intervals:
0 : 3.018
1 : 1.378
2 : 1.748
3 : 1.129
4 : 0.755
5 : 1.746
6 : 2.114
7 : 1.004
8 : 1.375
9 : 1.253
</pre>
=={{header|zkl}}==
{{trans|Python}}
<
while(True){
f:=File("/proc/stat"); // open each time to get fresh data
Line 831 ⟶ 1,377:
print("%5.1f%%\r".fmt(utilisation)); // stay on this line, overwrite old value
Atomic.sleep(5);
}</
{{out}}
Shown on multiple lines, in xterm output stays on one line, overwriting itself.
Line 845 ⟶ 1,391:
</pre>
{{omit from|VBA}}
{{omit from|Applesoft BASIC}}
|