Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/kernel/src/test/misc.c
1067 views
1
/*
2
This is meant to illustrate and test some things involving writing a C program
3
that runs using cowasm.
4
5
To build and run under CoWasm:
6
7
make run-misc.wasm
8
9
To build and run natively:
10
11
make run-misc.exe
12
13
*/
14
15
#include <stdio.h>
16
#include <stdlib.h>
17
#include <unistd.h>
18
#include <fcntl.h>
19
20
unsigned long long sum(int n) {
21
unsigned long long s = 0;
22
for (int i = 0; i <= n; i++) {
23
s += i;
24
}
25
return s;
26
}
27
28
#include <sys/time.h>
29
30
long long time0() {
31
struct timeval te;
32
gettimeofday(&te, NULL); // get current time
33
long long milliseconds =
34
te.tv_sec * 1000LL + te.tv_usec / 1000; // calculate milliseconds
35
// printf("milliseconds: %lld\n", milliseconds);
36
return milliseconds;
37
}
38
39
#include <sys/stat.h>
40
extern char* user_from_uid(uid_t uid, int nouser);
41
42
#include <limits.h>
43
int main(int argc, char** argv) {
44
#ifdef __cowasm__
45
printf("PAGE_SIZE=%d\n", PAGE_SIZE);
46
#endif
47
48
for (int i = 0; i < argc; i++) {
49
printf("argv[%d]=%s\n", i, argv[i]);
50
}
51
#ifdef __cowasm__
52
printf("hi %s\n", user_from_uid(500, 0));
53
#endif
54
55
const char* path = "/tmp/temporary-file";
56
57
int fd = open(path, O_RDWR | O_CREAT);
58
printf("opened '%s' with fd=%d usings flags=%d\n", path, fd, O_RDWR | O_CREAT);
59
if (fd == -1) {
60
fprintf(stderr, "file open failed!\n");
61
exit(1);
62
}
63
close(fd);
64
unlink(path);
65
66
int n = 10000000;
67
if (argc > 1) {
68
n = atoi(argv[1]);
69
}
70
if (n < 0) {
71
fprintf(stderr, "n must be nonnegative\n");
72
exit(1);
73
}
74
long long t0 = time0();
75
unsigned long long s = sum(n);
76
long long delta = time0() - t0;
77
printf("sum up to %d = %lld in %lldms\n", n, s, delta);
78
return 0;
79
}
80
81